0 like 0 dislike
53 views
In the PHP documentation, there where talk about integers and, in particular, about the translation to int from float, saying that rounding is toward zero and give you an example:

`<?php<br/>echo (int) ( (0.1+0.7) * 10 ); // echoes 7!?>`
And it really takes 7.
If you do

`echo (int) ( (0.2+0.7) * 10 )`

I understand that in the first case, eight is the number 7.999999 that as a result of rounding becomes seven.

Question(s) in the following:
1. On all cars will have such results?
2. Is this normal?
| 53 views

0 like 0 dislike
1. Yes. And on different platforms and with different compilers/interpreters (see answer barmaley_exe above).
2. Okay.
Google "floating point/comma" or read at least Wikipedia — much will become clear.
If you do not like, try to learn it.
\r
PS
\r
``\$ 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 ... ``
by
0 like 0 dislike
Where IEEE754 rules in terms of real numbers, must be so.
by
0 like 0 dislike
As I understand it, on the fingers this behaviour can be explained by the fact that 0.1 is not represented in the binary system as a finite fraction, and therefore is truncated in the translation.
by
0 like 0 dislike
7...
by
0 like 0 dislike
Yes, true.
While on the other hand, who knows how castes in page leads? :)
\r`[email protected]:~\$ php -R ' echo (int) ( (0.1+0.7) * 10 ),"\";'7[email protected]:~\$ php -R ' echo (int) ( (0.2+0.7) * 10 ),"\";'9[email protected]:~\$ php-vPHP 5.3.2-1ubuntu4.5 with Suhosin-Patch (cli) (built: Sep 17 2010 13:41:55) Copyright © 1997-2009 The PHP GroupZend Engine v2.3.0, Copyright © 1998-2010 Zend Technologies\r`
by
0 like 0 dislike
If you explain approximately, any real number is represented in memory with a certain, not absolute, accuracy (i.e., up to a certain bit).
\r
``\$ perl -e "printf('%.45f',0.1)" 0.100000000000000005551115123125782702118158340 \$ perl -e "printf('%.45f',0.7)" 0.699999999999999955591079014993738383054733276 \$ ruby -e "printf('%.45f',0.8)" 0.800000000000000044408920985006261616945266724 ``
by
0 like 0 dislike
For proper rounding you can use round()
by

0 like 0 dislike