Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

casting - PHP: float maths and comparisons

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

test.php

<?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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error progragation must be considered when several operations are compounded.

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 documentation page


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...