php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Problem with casting into (int) or intval()

Open VILQ opened this issue 4 years ago • 5 comments

Description

The following code:

<?php
$a = 42.85 * 100 - 34.84 * 100;
$b = (int)$a;
$c = (int)round($a);

echo $a."\n".$b."\n".$c;

Resulted in this output:

801
800
801

But I expected this output instead:

801
801
801

The result is consistent when we change '34.84' to e.g. '34.85', '34.86' or '34.83'. Eval link: https://3v4l.org/geEpE

When $b = intval($a) the result is the same.

PHP Version

8.0.22

Operating System

No response

VILQ avatar Feb 03 '22 15:02 VILQ

Floating point values have a limited precision. Hence a value might not have the same string representation after any processing. That also includes writing a floating point value in your script and directly printing it without any mathematical operations.

If you would like to know more about "floats" and what IEEE 754 is, read this: http://www.floating-point-gui.de/

Thank you for your interest in PHP.

cmb69 avatar Feb 03 '22 15:02 cmb69

So this one also acts "by design"? https://3v4l.org/kQk7Z

VILQ avatar Feb 03 '22 15:02 VILQ

@VILQ Yes. round() rounds up or down, (int) $foo always rounds down. echo rounds to the php.ini precision setting.

https://3v4l.org/JWAMR#v8.1.2

$x = 0.1 + 0.2;
var_dump($x);

echo $x. "\n";

ini_set('precision', -1);
echo $x, "\n";
float(0.30000000000000004)
0.3
0.30000000000000004

iluuu1994 avatar Feb 03 '22 16:02 iluuu1994

So you really didn't notice the difference between: Output for 8.0.1 - 8.0.15, 8.1.0 - 8.1.2 and Output for 7.4.0 - 7.4.27 ?

VILQ avatar Feb 03 '22 16:02 VILQ

The precision INI setting's default is changed as of PHP 8.0.0.

cmb69 avatar Feb 03 '22 16:02 cmb69