Hi!

Can some on explain why and how it is returning ‘1’ :

print (19.6 *100) !== (double)1960;

Thanks in advance

Hi!

Can some on explain why and how it is returning ‘1’ :

print (19.6 *100) !== (double)1960;

Thanks in advance

Floating point math

```
printf('%.20e', 19.6*100);
printf('%.20e', (double)1960);
// 1.96000000000000022737e+3
// 1.96000000000000000000e+3
```

As far as I’m aware, numbers after the decimal point are stored as fractions. The first bit is 1/2, the second is 1/4, the third is 1/8 etc. So for example the number 4.125 would be stored as 0100 0010 (simplified) because before the decimal is 4 (0100) and after the decimal is 1/8 (0010).

The problem arises when a number isn’t an exact fraction, to the amount of bits your computer can handle. It just so happens that .6 may not be possible by an addition of finite fractions (all being 2^-n) so it cannot be stored as an exact number.

hang on a minute, print (19.6 *100) returns 1, and that’s what’s being compared isn’t it? … oh no i’m completely wrong there i think. silly me.

yup, it’s as hash demonstrated: the internal representations, at a very precise level of detail (in their enirity that is), do differ. presumably because the two numbers were arrived at in different ways, and because of the inherent inacuracies of decimal fractions in a binary system as Jake is getting at.

The comparison is asking if they are not equal - and therefore an output of 1 shows that they aren’t.

yup but the 1 you’re talking about is a different 1 i was talking about.

$x = print (19.6 *100);

$x now contains 1 because print returns 1.

i thought to start with, incorrectly, what was happening is what this code gets at:

(print (19.6 *100)) !== (double)1960;

print prints, and returns a value; 1. but it was nothing to do with that i now know.

I see what you mean