Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with casting into (int) or intval() #8028

Closed
VILQ opened this issue Feb 3, 2022 · 5 comments
Closed

Problem with casting into (int) or intval() #8028

VILQ opened this issue Feb 3, 2022 · 5 comments

Comments

@VILQ
Copy link

VILQ commented Feb 3, 2022

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

@cmb69
Copy link
Contributor

cmb69 commented Feb 3, 2022

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.

@VILQ
Copy link
Author

VILQ commented Feb 3, 2022

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

@iluuu1994
Copy link
Member

@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

@VILQ
Copy link
Author

VILQ commented Feb 3, 2022

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
?

@cmb69
Copy link
Contributor

cmb69 commented Feb 3, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants