Vinod
Vinod

Reputation: 32861

Decimal comaprison in Java script

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.

Upvotes: 1

Views: 2569

Answers (5)

dongilmore
dongilmore

Reputation: 624

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".

Upvotes: 0

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827536

You can also do type casting:

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

Number(a) == Number(b) // This will be true

Upvotes: 2

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

Maybe you can try parseFloat() like this:

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

parseFloat() concerts Strings to float.

Upvotes: 0

eyelidlessness
eyelidlessness

Reputation: 63529

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

But heed unwind's answer.

Upvotes: 0

unwind
unwind

Reputation: 399891

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.

Upvotes: 3

Related Questions