0

I have a situation where I cast a double variable to integer. and its giving me wrong result. Why is this happening?

>>> $amount = (double) 1052.10 => 1052.1 >>> $amount = $amount * 100; => 105210.0 >>> (int) $amount; => 105209 // weird 

I am able to fix it by rounding the variable first ( ie: (int) round($amount)),

But still, I wonder why is this happening?

using PHP 7.2.9

1

1 Answer 1

0

The 'warning' section here states:

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision.

Sign up to request clarification or add additional context in comments.

2 Comments

Why would intval work? This essentially does the same thing as casting.
@Devon You're right, I did some more testing and the output seems to be the same, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.