Z
Z
zeban2010-10-12 14:36:16
PHP
zeban, 2010-10-12 14:36:16

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 )



  1. Whether on all machines there will be such results?
  2. This is fine?

Answer the question

In order to leave comments, you need to log in

7 answer(s)
K
keatis, 2010-10-12
@zeban

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

[
[email protected]><e, 2010-10-12
@barmaley_exe

Where IEEE754 rules in terms of real numbers, it should be so.

M
m00t, 2010-10-12
@m00t

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.

A
Alexey, 2010-10-12
@alexxxst

7…

B
biophreak, 2010-10-12
@biophreak

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

K
keatis, 2010-10-12
@keatis

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

Z
ZxAnderson, 2010-10-12
@ZxAnderson

For proper rounding, you can use round()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question