VoW*_*VoW 5 php floating-point double int floating-point-precision
当我使用(int)和(double)一些时,它无法正常工作.
看看PHP代码示例:
我需要离开2个小数并删除其他...
我知道number_format(); 功能但我不能使用它.因为它是舍入数
number_format(24.299,2);
输出:24.30
我需要:24.29
<?php
$str="158.2";
echo (double)$str; // Output: 158.2
echo (double)$str*100; // Output: 15820
echo (int)((double)$str*100); // Output: 15819 <-WHY? It Must To Be 15820, Why 15819?
echo ((int)((double)$str*100)/100); // Output: 158.19
?>
Run Code Online (Sandbox Code Playgroud)
我需要在数字中留下两位小数,并在不进行舍入的情况下剪切其他小数.
由于浮点精度(例如,见这个问题:的PHP -浮动号码精密),158.2 * 100是不准确 15820,但像15819.99999999.
现在(int)用于类型转换,而不是用于舍入,并且该点之后的任何数字都被切除.
我需要在数字中留下两位小数,并在不进行舍入的情况下剪切其他小数.
这很简单:
number_format($str, 2);
Run Code Online (Sandbox Code Playgroud)
更新
number_format 不圆的,所以它是一个比较复杂:
bcmul($str,100,0)/100
Run Code Online (Sandbox Code Playgroud)
bcmul 乘以任意精度,在这种情况下为0.结果:
bcmul(158.2,100,0)/100 == 158.2
bcmul(24.299,100,0)/100 == 24.29
Run Code Online (Sandbox Code Playgroud)