Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a decimal number based on certain values in php

I am having few values 99.00 99.90 99.01

FYI, I am already getting the above 3 values after having number_format($value, 2) applied to them

But now I want to strip the decimals without rounding them off such as 99.00 to 99 99.90 to 99.9 99.01 to 99.01 remains same

How can achieve this? Please devise me a way guys.

I just need a function which checks following:

  1. Whether a given number is decimal i.e having "." and digits after decimal
  2. Whether the last digit is 0, if yes, then get rid of the last digit
  3. Whether both the digits after decimal points are 0, if yes, remove them.
  4. If any of them are not 0, then they should remain there, like in case of 99.09 it should remain intact, in case of 99.90 it should be 99.9.

Awaiting your ideas. Thanks in advance.

like image 761
Asnexplore Avatar asked Jan 26 '18 15:01

Asnexplore


2 Answers

By adding 0 to the number, the rightmost zeros are removed:

$num1 = 99.00;
$num2 = 99.90;
$num3 = 99.01;
$num4 = 99.012;
$num5 = 99.0123;

$num1 = number_format(99.00,   2, '.', '') + 0;
$num2 = number_format(99.90,   2, '.', '') + 0;
$num3 = number_format(99.01,   2, '.', '') + 0;
$num4 = number_format(99.012,  2, '.', '') + 0;
$num5 = number_format(99.0123, 2, '.', '') + 0;

echo "$num1\n";
echo "$num2\n";
echo "$num3\n";
echo "$num4\n";
echo "$num5\n";

Output:

99
99.9
99.01
99.01
99.01

Try it here.

With a function:

function round2no0(&$num)
{
    $num = number_format($num, 2, '.', '') + 0;
}

usage:

$num1 = 99.00;
$num2 = 99.90;
$num3 = 99.01;
$num4 = 99.012;
$num5 = 99.0123;

round2no0($num1);
round2no0($num2);
round2no0($num3);
round2no0($num4);
round2no0($num5);

echo "$num1\n";
echo "$num2\n";
echo "$num3\n";
echo "$num4\n";
echo "$num5\n";

function round2no0(&$num)
{
    $num = number_format($num, 2, '.', '') + 0;
}

Output:

99
99.9
99.01
99.01
99.01

Edit:

Added , '.', '' parameters to number_format to handle also numbers with thousands maintaining the machine-format 12345.12.

Try it here.

like image 191
user2342558 Avatar answered Sep 27 '22 22:09

user2342558


you should be able to just wrap it in a floatval()

like image 38
Jake Pogorelec Avatar answered Sep 27 '22 22:09

Jake Pogorelec