Reputation: 27
console.log(typeof(parseInt((0.1 + 0.2).toFixed(1)))); // number
console.log((0.1 + 0.2).toFixed(1) == 0.3); // true
console.log((parseInt((0.1 + 0.2).toFixed(1))) === 0.3); // false
Can someone please explain why the last statement does not return true?
Upvotes: 1
Views: 375
Reputation: 11
Remember that parseInt() converts to an integer, so JavaScript rounds.
So:
parseInt(0.1+0.2)
always returns 0. 0 is a number so this returns true.(0.1 + 0.3)
returns 0.3, meaning that this statement is true.parseInt(0.1 + 0.3)
rounds to 0 so this returns false.Upvotes: 1
Reputation: 786
parseInt will retrieve only integer value. In your case, parseInt(0.3) will return 0 which is not equal to 0.3 Go with Number(0.3) instead of using parseInt.
Upvotes: 0
Reputation: 370989
parseInt
will try to turn its argument into an int (integer). Decimal values will turn into integers. So
(0.1+0.2).toFixed(1)
turns into 0.3
, and
parseInt((0.1+0.2).toFixed(1))
turns into 0 (because parseInt
floors non-integers, and 0.3 floored is 0).
If you just want to cast to number, use Number
instead:
console.log((Number((0.1+0.2).toFixed(1)))===0.3);
Keep in mind that due to floating-point weirdness, 0.1 + 0.2
results in 0.30000000000000004
- that's why calling toFixed
on it first, to trim off some of the decimal points, is needed to compare it against 0.3
properly.
Upvotes: 7
Reputation: 62
It is because you are using parseInt(0.1 + 0.2)
. parseInt
converts it to an integer and acts like floor
, so parseInt(0.3)
is giving 0
Upvotes: 1