Search code examples
phpnumber-formatting

Formatting a number


I have a table with numbers like these:

19809.1
1982.0
1982.19

Its currency. Is there a function I can use to format these numbers like this?

19 809,10
1 982,00
1 982,19

Solution

  • This is quite easy with number_format:

    number_format(value, number_of_decimals, "decimal_separator", "thousand_separator")
    

    Something like this:

    echo number_format(19809.1, 2, ",", " ");
    

    This tells the number to have 2 decimals, comma , as decimal separator and a whitespace as thousand separator. Output will be:

    19 809,10
    

    Other examples:

    echo number_format(19809.1, 0, "", ".");
    > 19.809
    > no decimal and . as thousand separator
    
    echo number_format(19809.1, 3, ".", ",");
    > 19,809.100
    > 3 decimals, comma as thousand separator and dot as decimal separator