javascriptfloating-pointnumberscomparison

Javascript float comparison


I'm having a big problem with number comparison in javascript.

The script accuses that the comparison "7 < 10" is false.

console.clear();

var min = parseFloat("5").toFixed(2);
var max = parseFloat("10").toFixed(2);
var value = parseFloat("7").toFixed(2);

console.log(min, max, value);

console.log(value > min); // OK.
console.log(value < max); // ---- false ??????

Anyone knows what is happing?


Solution

  • As it turns out .toFixed() returns strings - Try adding parseFloat before comparing the values to see the result:

    console.log(parseFloat(value) < parseFloat(max)); // ---- now true