number_format() php remove trailing zeros

て烟熏妆下的殇ゞ 提交于 2020-07-06 20:58:20

问题


Is there a way with number_format() to leave out decimal places if the number is not a float/decimal?

For example, I would like the following input/output combos:

50.8 => 50.8
50.23 => 50.23
50.0 => 50
50.00 => 50
50 => 50

Is there a way to do this with just a standard number_format()?


回答1:


You can add 0 to the formatted string. It will remove trailing zeros.

echo number_format(3.0, 1, ".", "") + 0; // 3

A Better Solution: The above solution fails to work for specific locales. So in that case, you can just type cast the number to float data type. Note: You might loose precision after type casting to float, bigger the number, more the chances of truncating the number.

echo (float) 3.0; // 3

Ultimate Solution: The only safe way is to use regex:

echo preg_replace("/\.?0+$/", "", 3.0); // 3
echo preg_replace("/\d+\.?\d*(\.?0+)/", "", 3.0); // 3

Snippet 1 DEMO

Snippet 2 DEMO

Snippet 3 DEMO




回答2:


If you want to use whitespace here is better solution

function real_num ($num, $float)
{
    if (!is_numeric($num) OR is_nan($num)  ) return 0;

    $r = number_format($num, $float, '.', ' ');

    if (false !== strpos($r, '.'))
        $r = rtrim(rtrim($r, '0'), '.');

    return $r;
} 


来源:https://stackoverflow.com/questions/49890550/number-format-php-remove-trailing-zeros

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