且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

php浮点数计算小数点后2位

更新时间:2023-02-21 16:08:36

试试 sprintf("%.2f", $c);

浮点数以 IEEE 表示法表示,基于 2 的幂,因此终止十进制数可能不是终止二进制数,这就是您得到尾随数字的原因.

Floating point numbers are represented in IEEE notation based on the powers of 2, so terminating decimal numbers may not be a terminating binary number, that's why you get the trailing digits.

正如可变长度编码器所建议的那样,如果您知道所需的精度并且它不会改变(例如,当您处理金钱时),***只使用定点数,即将数字表示为美分而不是比美元

As suggested by Variable Length Coder, if you know the precision you want and it doesn't change (e.g. when you're dealing with money) it might be better to just use fixed point numbers i.e. express the numbers as cents rather than dollars

$a = 3456;

$b = 3455;

$c = $b - $a;

sprintf ("%.2f", $c/100.0);

这样,如果您在打印前进行大量计算,就不会出现任何舍入错误.

This way, you won't have any rounding errors if you do a lot of calculations before printing.