Search code examples
phpnumbers

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

  • 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