Joe*_*tto 4 php floating-point numbers decimal number-formatting
有没有一种方法number_format()
来离开了小数,如果数字是不是float /十进制?
例如,我想要以下输入/输出组合:
50.8 => 50.8
50.23 => 50.23
50.0 => 50
50.00 => 50
50 => 50
Run Code Online (Sandbox Code Playgroud)
有没有办法用一个标准的方法做到这一点number_format()
?
您可以添加0
到格式化的字符串。它将删除尾随零。
echo number_format(3.0, 1, ".", "") + 0; // 3
Run Code Online (Sandbox Code Playgroud)
更好的解决方案:上述解决方案不适用于特定的语言环境。因此,在这种情况下,您只需将数字float
类型转换为数据类型即可。注意:将类型强制转换为时float
,可能会降低精度,数字越大,截断数字的机会就越大。
echo (float) 3.0; // 3
Run Code Online (Sandbox Code Playgroud)
最终解决方案:唯一安全的方法是使用正则表达式:
echo preg_replace("/\.?0+$/", "", 3.0); // 3
echo preg_replace("/\d+\.?\d*(\.?0+)/", "", 3.0); // 3
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1578 次 |
最近记录: |