Answer the question
In order to leave comments, you need to log in
Rounding in PHP
In the documentation for PHP, where they talk about integers and, in particular, about converting to int from float, they say that rounding goes towards zero and give the following example:
And it really displays 7 for
me
. 9.
I understand that in the first case, the eight is the number 7.999999, which, as a result of rounding, becomes a seven.
Question(s) as follows:
<?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>
echo (int) ( (0.2+0.7) * 10 )
Answer the question
In order to leave comments, you need to log in
1. Yes. And on different platforms, and on different compilers/interpreters (see barmaley_exe's answer above).
2. Normal.
Google “floating point / comma numbers” or read at least Wikipedia - a lot will become clear.
If you don't like it, try to know it .
PS
$ perl -e "print int((0.1+0.7) * 10)"
7
$ perl -e "print int((0.1+0.7) * 10)"
9
$ perl -v
This is perl, v5.10.1 (*) built for i386-freebsd
...
Where IEEE754 rules in terms of real numbers, it should be so.
As far as I understand, on the fingers, this behavior can be explained by the fact that 0.1 is not represented in the binary system as a final fraction, and therefore is cut off during translation.
Yes, indeed.
Although, on the other hand, does anyone know how the cast behaves in puff? :)
[email protected]:~$ php -r'echo (int) ( (0.1+0.7) * 10 ),"\n";'
7
[email protected]:~$ php -r'echo (int) ( (0.2+0.7) * 10 ),"\n";'
9
[email protected]:~$ php -v
PHP 5.3.2-1ubuntu4.5 with Suhosin-Patch (cli) (built: Sep 17 2010 13:41:55)
Copyright © 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright © 1998-2010 Zend Technologies
If explained approximately, then any real number is represented in memory with some, not absolute, accuracy (ie, up to a certain binary digit).
$ perl -e "printf('%.45f',0.1)"
0.100000000000000005551115123125782702118158340
$ perl -e "printf('%.45f',0.7)"
0.699999999999999955591079014993738383054733276
$ ruby -e "printf('%.45f',0.8)"
0.800000000000000044408920985006261616945266724
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question