'How can I format this number correctly using PHP?

I have a number with numbers after the decimal but for some reason when formatting it, the last two decimals are always zero.

For example a price is 154,95 as saved in my database, but I would like a number of 150 to be shown like 150,00. So I looked up number_format() and found this info:

number
The number being formatted.

decimals
Sets the number of decimal points.

dec_point
Sets the separator for the decimal point.

thousands_sep
Sets the thousands separator.

With above info I did this:

echo number_format($artikel['prijs'],2,",",".");

The comma should be the decimal seperator and the dot the thousands seperator. Still the result of 154,95 with above code is 154,00 , why?

I want all numbers to have the same format, a number with two decimals behind the comma wether these are zero or more.



Solution 1:[1]

The problem is that first the price "154,95" is converted to number as 154, and after that number_format() starts to do his job. Either you have to store in the database the price as 154.95, or you have to replace the character "," with "." before calling number_format(). Example:

<?php
$a = "159.95";
$b = "12345";
$a_number = str_replace(",", ".", $a);
$b_number = str_replace(",", ".", $b);

echo number_format($a_number,2,",","."), "\n";
echo number_format($b_number,2,",","."), "\n";
?>

And the output is:

159,95

12.345,00

Solution 2:[2]

Change your enter number format.

<?php
echo number_format("1000000")."<br>";
echo number_format("1000000",2)."<br>";
echo number_format("1000000",2,",",".");
?>

Output:-

1,000,000
1,000,000.00
1.000.000,00

Solution 3:[3]

This will round your number to the nearest multiple of 10:

$n = 123.45;

$multiple = 10;

$result = (ceil($n)%$multiple === 0) ? ceil($n) : round(($n+$multiple/2)/$multiple)*$multiple;

echo $result;

Then number_format() converts it to a string for display with the seperators (,.). In different locations they have the comma to seperate decimals and the stop to seperate thousands and vice versa in other locations so I usually leave those parameters out as they are optional anyway and I think it might change depending on the locale settings on the machine viewing it but I am not sure about that.

So I'd add:

$display_result = number_format($result,2);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Nimesh Patel
Solution 3 Paddy Hallihan