PHP number format

20,768

Solution 1

From the PHP Manual page on number_format:

string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )

If you want numbers like 123456 be formatted as 1234,45, use:

echo number_format($number / 100, 2, ",", "");

If you need a dot as thousands separator (1.234,56):

echo number_format($number / 100, 2, ",", ".");

The zeros are automatically removed by PHP when converting the string to a number.

Solution 2

string number_format ( float $number , 
                       int $decimals = 0 ,
                       string $dec_point = '.' ,
                       string $thousands_sep = ',' )

Manual: http://php.net/manual/en/function.number-format.php

// divide by 100 to shift ones place.
echo number_format((int)'000000000000100' / 100,2,',','');
Share:
20,768
Ste
Author by

Ste

Updated on July 23, 2022

Comments

  • Ste
    Ste almost 2 years

    I have this string :

    000000000000100
    

    and need to convert it to:

    1,00
    

    So, the rules are:

    1. Divide the number by 100 and use a comma as decimal separator
    2. Strip leading zeros
    3. Keep two decimals
  • Brad Christie
    Brad Christie almost 13 years
    err, divide is what i meant.
  • Eoin
    Eoin about 6 years
    Brad, you should write the outcome as well so it's a clearer example for noobs like me. I assume it is 0000000000001,00.
  • Eoin
    Eoin about 6 years
    This confused me for ages because I was thinking "but where does ", " (comma space) appear in the end result". Now I see the comma separates the values and one is within quotes. :D