PHP - 浮点数精度 [英] PHP - Floating Number Precision

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

问题描述

$a = '35';
$b = '-34.99';
echo ($a + $b);

结果为 0.009999999999998

Results in 0.009999999999998

这是怎么回事?我想知道为什么我的程序总是报告奇怪的结果.

What is up with that? I wondered why my program kept reporting odd results.

为什么 PHP 不返回预期的 0.01?

Why doesn't PHP return the expected 0.01?

推荐答案

因为浮点运算 != 实数运算.由于不精确而导致的差异的一个例子是,对于某些浮点数 ab(a+b)-b != a.这适用于任何使用浮动的语言.

Because floating point arithmetic != real number arithmetic. An illustration of the difference due to imprecision is, for some floats a and b, (a+b)-b != a. This applies to any language using floats.

由于 floating point 是精度有限的二进制数,所以 可表示的数字,导致准确性问题 和诸如此类的惊喜.这是另一个有趣的读物:每个计算机科学家都应该了解的关于浮点运算的知识.

Since floating point are binary numbers with finite precision, there's a finite amount of representable numbers, which leads accuracy problems and surprises like this. Here's another interesting read: What Every Computer Scientist Should Know About Floating-Point Arithmetic.

回到你的问题,基本上没有办法用二进制准确表示 34.99 或 0.01(就像十进制一样,1/3 = 0.3333...),所以使用近似值.要解决此问题,您可以:

Back to your problem, basically there is no way to accurately represent 34.99 or 0.01 in binary (just like in decimal, 1/3 = 0.3333...), so approximations are used instead. To get around the problem, you can:

  1. 使用round($result, 2) 将结果四舍五入到小数点后两位.

  1. Use round($result, 2) on the result to round it to 2 decimal places.

使用整数.如果是货币,例如美元,则将 35.00 美元存储为 3500,将 34.99 美元存储为 3499,然后将结果除以 100.

Use integers. If that's currency, say US dollars, then store $35.00 as 3500 and $34.99 as 3499, then divide the result by 100.

遗憾的是 PHP 没有像 other 那样的十进制数据类型语言 做.

It's a pity that PHP doesn't have a decimal datatype like other languages do.

这篇关于PHP - 浮点数精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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