php浮点运算2小数点 [英] php float calculation 2 decimal point

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

问题描述

  $ a = 34.56 

$ b = 34.55

$ a

$ code $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b $ p
$ b $ $ $ $ $ $ $ $ $ $ $ >

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



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



如何确保 $ a $ b 2位小数,后面没有隐藏数字。

在我的php知识中只有number_format能够格式化显示,但是值不是真正的2位十进制,



我希望能从这里得到帮助。这真让我感到沮丧。 sprintf (%。2f,$ c);
浮点数用IEEE的符号表示,基于2的幂,所以终止十进制数可能不是终止二进制数,这就是为什么你会得到结尾数字。



正如变长编码器所建议的那样,如果你知道你想要的精度并且不会改变(例如当你处理钱时)更好地使用定点数字,即将数字表示为美分而不是美元。

$ b = 3455;

$ c = $ b - $ a;

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

这样,如果在打印之前进行大量计算,则不会有任何舍入错误。

Got another math calculation problem again.

$a = 34.56

$b = 34.55

$a do some calculation to get this figure

$b is doing rounding nearest 0.05 to get this figure

what happen is

$c = $b - $a

supposedly I should be -0.01, but I echo out the $c is show -0.00988888888888

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

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

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

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

解决方案

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

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天全站免登陆