Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
Alexandre Perez Avatar asked Feb 10 '14 23:02

Alexandre Perez


People also ask

Can we use == to compare two float values?

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.

How do you compare two floats?

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.

How do you compare decimals in JavaScript?

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.

Can you compare floats in Java?

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.


1 Answers

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 
like image 116
prototype Avatar answered Sep 21 '22 07:09

prototype