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

问题描述

我希望所有下面的比较是bool(true),但他们不是。
任何人都可以解释这个问题吗?

I would expect all below comparisons to be bool (true) but they are not.Can anyone explain this?

<?php

$f = 12;
$f += 5.95;
$f += 5.95;
$f += 5.95;

echo 'var_dump($f) = ';
var_dump($f);

echo 'var_dump($f == \'29.85\') = ';
var_dump($f == '29.85');

echo 'var_dump($f == 29.85) = ';
var_dump($f == 29.85);

echo 'var_dump($f == (float)\'29.85\') = ';
var_dump($f == (float)'29.85');

echo 'var_dump($f == \'29.85\') = ';
var_dump((string)$f == '29.85');

echo 'var_dump(round($f, 2) == \'29.85\') = ';
var_dump(round($f, 2) == '29.85');

$ php test.php

$ php test.php

var_dump($f) = float(29.85)
var_dump($f == '29.85') = bool(false)
var_dump($f == 29.85) = bool(false)
var_dump($f == (float)'29.85') = bool(false)
var_dump($f == '29.85') = bool(true)
var_dump(round($f, 2) == '29.85') = bool(true)

$ php -v

PHP 5.2.14 (cli) (built: Jul 23 2010 15:23:00)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2010 Zend Technologies
    with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans


推荐答案

有理数可以精确表示为
基数10中的浮点数,如0.1或0.7,没有
精确表示为基数2中的浮点数,这是内部使用的
,无论尾数的大小。因此,它们
不能被转换为它们的内部二进制对等体而没有
小的精度损失。这可能导致混乱的结果:对于
示例,floor((0.1 + 0.7)* 10)通常将返回7而不是
预期8,因为内部表示将像
7.9999999999999991118 ....

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

因此,不要将浮点数结果与最后一位数相关联,永远不要
比较浮点数是否相等。

So never trust floating number results to the last digit, and never compare floating point numbers for equality.

这篇关于PHP:浮点数学和比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:42
查看更多