views:

996

answers:

6

I am trying to compare two decimal values in Java script. I have two objects as one assogned value "3" and the other as "3.00". When i say if (obj1 == obj2) it does not pass the condition as it is does the string comparision.

I would instead want it to do a decimal comparision where 3 = 3.00. Please let me know how to do this.

+2  A: 

This page describes how to convert a string to a floating-point number; I believe that is what you want. This would let you compare the numbers as numbers, which I think is what you mean by "decimally". Beware that doing an exact comparison between two floating-point numbers is often considered a bit "hazardous", since there are precision issues that might cause two numbers that you would consider "equal" to not compare as such. See, for instance, What Every Computer Scientist Should Know About Floating-Point Arithmetic, which is a classic text on the topic. Perhaps a bit on the advanced side, but try searching for something more basic in that case.

unwind
thank you very much. This worked for me... :)
Vinodtiru
A: 
if(parseFloat(obj1) == parseFloat(obj2)) { // ...

But heed unwind's answer.

eyelidlessness
A: 

Both objects are being treated as strings and so they naturally differ from each other. Use this instead:

if (parseFloat(obj1) == parseFloat(obj2)) {

}

Abbas
A: 

Maybe you can try parseFloat() like this:

if(parseFloat(obj1) == parseFloat(obj2))

parseFloat() concerts Strings to float.

Vincent Ramdhanie
+2  A: 

You can also do type casting:

var a = "3.00";
var b = "3";

Number(a) == Number(b) // This will be true
CMS
A: 

As strings, they are not equal. As integers, they are, but your example implies float and this is a problem. Avoid equality comparisons of float numbers due to their nature: their precision is limited, and after miscellaneous arithmetic, you might end up comparing numbers like 1.0 and .99999999999 and getting "not equal".

dongilmore