Rounding in PHP


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
6 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 )

It already displays 9.

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?
by | 6 views

7 Answers

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? :)
\rb@thinkpad:~$ php -R ' echo (int) ( (0.1+0.7) * 10 ),"\";'
7
b@thinkpad:~$ php -R ' echo (int) ( (0.2+0.7) * 10 ),"\";'
9
b@thinkpad:~$ 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
\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

Related questions

0 like 0 dislike
5 answers
asked Apr 1, 2019 by nepster-web
0 like 0 dislike
5 answers
asked Apr 1, 2019 by nepster-web
0 like 0 dislike
1 answer
asked Aug 10, 2019 by Adven0104
0 like 0 dislike
2 answers
0 like 0 dislike
3 answers
asked May 10, 2019 by sladenkij
110,608 questions
257,186 answers
0 comments
28,049 users