number_format()php删除尾随零

问题描述 投票:3回答:1

如果数字不是浮点数/小数,有没有办法让number_format()省略小数位?

例如,我想要以下输入/输出组合:

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

有没有办法用标准的number_format()做到这一点?

php floating-point numbers decimal number-formatting
1个回答
5
投票

您可以将0添加到格式化的字符串中。它将删除尾随零。

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

更好的解决方案:上述解决方案无法适用于特定的区域设置。因此,在这种情况下,您只需键入强制转换为float数据类型。注意:在向float进行类型转换后,您可能会失去精度,数字越大,截断数字的可能性就越大。

echo (float) 3.0; // 3

终极解决方案:唯一安全的方法是使用正则表达式:

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

© www.soinside.com 2019 - 2024. All rights reserved.