PHP number format

廉价感情. 提交于 2019-11-26 17:29:21

问题


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

回答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.




回答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,',','');


来源:https://stackoverflow.com/questions/6308687/php-number-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!