简体   繁体   English

number_format() php 删除尾随零

[英]number_format() php remove trailing zeros

Is there a way with number_format() to leave out decimal places if the number is not a float/decimal?如果数字不是浮点数/小数,有没有办法用number_format()小数位?

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() ?有没有办法只用一个标准的number_format()来做到这一点?

You can add 0 to the formatted string.您可以将0添加到格式化字符串中。 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.因此,在这种情况下,您只需将数字类型转换为float数据类型即可。 Note: You might loose precision after type casting to float , bigger the number, more the chances of truncating the number.注意:将类型转换为float后可能会降低精度,数字越大,截断数字的机会越大。

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片段 1 演示

Snippet 2 DEMO片段 2 演示

Snippet 3 DEMO片段 3 演示

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;
} 

Use:用:

$a = 50.00; $a = 50.00;

$a = round($a, 2); $a = round($a, 2);

Even though the number has 2 zeros trailing it, if you round it, it won't show the decimal places, unless they have some kind of value.即使该数字后面有 2 个零,如果您对它进行四舍五入,它也不会显示小数位,除非它们具有某种值。

so 50.00 rounded using 2 places will be 50, BUT 50.23 it will be 50.23所以使用 2 个位置四舍五入的 50.00 将是 50,但 50.23 将是 50.23

Thank you, yes thank you.谢谢,是的,谢谢。 So EASYYYY.所以很容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM