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?
Because comparing floats with == is problematic, it's unwise to use them as IDs; the names in your example code suggest that's what you are doing; long integers (longs) are preferred, and the de facto standard for IDs.
To compare two floating point or double values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.
To compare decimal numbers with JavaScript, we can round both numbers and then compare them. to multiply a and b by 100 and call Math. round with the returned number to get rid of the decimals. Then we use > to compare them.
The compare() method of Float Class is a built-in method in Java that compares the two specified float values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call. Parameters: The function accepts two parameters: f1: The first float value to be compared.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With