php浮点数计算小数点后2位 [英] php float calculation 2 decimal point

查看:24
本文介绍了php浮点数计算小数点后2位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一道数学计算题.

$a = 34.56

$b = 34.55

$a做一些计算得到这个数字

$a do some calculation to get this figure

$b 正在四舍五入到最接近的 0.05 以获得这个数字

$b is doing rounding to the nearest 0.05 to get this figure

发生了什么

$c = $b - $a

应该是-0.01,但是我回显了$c,它显示了-0.00988888888888

supposedly it be -0.01, but I echo out the $c, which shows -0.00988888888888

我尝试使用number_format($c, 2),但是输出是0.00,

I try to use number_format($c, 2), but the output is 0.00,

如何确保 $a$b 正好是 2 位小数,后面没有隐藏数字.

how can I make sure $a and $b is exactly 2 decimals, no hidden number at the back.

在我的php知识中,number_format只能格式化显示,但值并不是真正的2位小数,

in my php knowledge, number_format is only able to format the display, but the value is not really 2 decimal,

我希望我能从这里得到帮助.这让我很沮丧.

I hope I can get help from here. This really frustrated me.

推荐答案

试试 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.

这篇关于php浮点数计算小数点后2位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆