1

I would like to know why returns false the var_dump in the last case

var_dump(66*0.1);
var_dump(6.6);
var_dump((66*0.1) == 6.6);

The output:

float(6.6)
float(6.6)
bool(false)

if I use round it works fine:

var_dump(round(66*0.1, 1) == 6.6);
bool(true)

Can someone describe me what is wrong with the php floats?

MrRP
  • 822
  • 2
  • 10
  • 25

2 Answers2

2

This problem is inherited from C language.

There will be a small difference while comparing floating values,

See this, ans this

try this,

if (abs((6.6 - 6.6)/ 6.6) < 0.00001) {
    echo '<br />Both are equal ';
}
else{
    echo '<br />Both are not equal ';
}
Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
0

Probably because PHP like most programming languages and CPUs cannot represent floating point numbers exactly. Refer to this article for details: https://en.wikipedia.org/wiki/Floating_point

mlewis54
  • 2,372
  • 6
  • 36
  • 58
  • Almost. The binary system cannot represent *some* floating point numbers exactly. – Bart Friederichs Oct 29 '15 at 15:09
  • That's true. It's because the actual number is represented as a value between 0 and 1 (ignoring negative numbers for now) which is multiplied by the exponent of the FP number. The actual number, as you say, cannot be exactly represented by a binary number unless it's a power of 2 or zero. – mlewis54 Oct 29 '15 at 15:13