How to format decimal based on specific values ​​in php

I have several values ​​99.00 99.90 99.01

FYI, I already get the above 3 values ​​after the format_number is added to them ($ value, 2)

But now I want to break the decimal places without rounding them, for example 99.00 to 99 99.90 to 99.9 99.01 - 99.01 remains the same

How can this be achieved? Please come up with me guys.

I just need a function that checks the following:

  • Is the given number decimal, having "." and numbers after decimal
  • If the last digit is 0, if so, get rid of the last digit
  • Will both digits after decimal points be 0, if so, delete them.
  • If any of them is not 0, then they should remain there, for example, in the case of 99.09 it should remain intact, in the case of 99.90 it should be 99.9.

Waiting for your ideas. Thanks in advance.

+6
source share
4 answers

Adding 0to 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 the help offunction :

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

using:

$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 , '.', ''in number_formatto handle also numbers with thousands supporting the machine format 12345.12.

Try it here .

+3
source

you can just wrap it in floatval()

+1
source

:

echo round(99.001, 2), PHP_EOL;
echo round(99.901, 2), PHP_EOL;
echo round(99.011, 2), PHP_EOL;

:

99
99.9
99.01
0

number_format, preg_replace, .

// Default notation
echo preg_replace('/\.?0+$/', '', number_format(9990.00, 2)); // "9,990"
echo preg_replace('/\.?0+$/', '', number_format(9990.90, 2)); // "9,990.9"
echo preg_replace('/\.?0+$/', '', number_format(9990.01, 2)); // "9,990.01"

// French notation
echo preg_replace('/,?0+$/', '', number_format(9990.00, 2, ',', ' ')); // "9 990"
echo preg_replace('/,?0+$/', '', number_format(9990.90, 2, ',', ' ')); // "9 990,9"
echo preg_replace('/,?0+$/', '', number_format(9990.01, 2, ',', ' ')); // "9 990,01"
0
source

All Articles