mongkon yapon
mongkon yapon

Reputation: 21

Why javascript comparision number incorrect?

Why javascript comparision number incorrect ?

It's very simple but why incorrect (alert false)?

<script>
  var xxx = "112.77";
  alert(xxx);
  if(xxx < '2.50')
  {
      alert("false");     
  }
  else
  {
      alert("true");          
  }
</script>

https://jsfiddle.net/sp82ehqp/

Upvotes: 2

Views: 100

Answers (5)

Nina Scholz
Nina Scholz

Reputation: 386680

You could convert at least one to number with an unary + and compare then.

Strings are compared by character for character.

As you see, if one of the value is a number, the comparison is made by number.

var xxx = "112.77";
console.log(xxx);
console.log(xxx < '2.50');   // true
console.log(+xxx < +'2.50'); // false
console.log(xxx < +'2.50');  // false
console.log(+xxx < '2.50');  // false

Upvotes: 3

Ferus7
Ferus7

Reputation: 727

you are comparing strings, parse them to Number

var xxx = 112.77;
  alert(xxx);
  if(xxx < 2.50)
  {
     alert("false");     
 }
 else
  {
  alert("true");          

}

Upvotes: 0

Grasshopper
Grasshopper

Reputation: 1769

JavaScript will do type conversion if one of the objects is a number and the other is a string. So if for some reason your xxx variable is a string all you have to do is change the type of 2.50:

 var xxx = "112.77";


  alert(xxx);
  if(xxx < 2.50 )
  {
      alert("false");     
  }
  else
  {
      alert("true");          
  }

Upvotes: 1

Alicia Sykes
Alicia Sykes

Reputation: 7107

That's because your using String, rather than a number. Just remove the "".

Here's your updated JSFiddle

  var x = 112.77;
  alert(x);
  if (x < 2.50) {
    alert(false);
  } else {
    alert(true);
  }


Dynamic Data Types in JavaScript

In JavaScript numbers, strings and Booleans are identified by their punctuation. e.g.:

var foo = 42;    // foo is now a Number
var foo = 'bar'; // foo is now a String
var foo = true;  // foo is now a Boolean

Read more about JavaScript basic data types


Converting Strings to Numbers

If your unable to define your number as a number (e.g. your pulling it from an input field). Then you can convert it using Number(). If your number is an integer, you can also use parseInt().

Number('123')     // 123
Number('12.3')    // 12.3
Number('')        // 0
Number('0x11')    // 17
Number('0b11')    // 3
Number('0o11')    // 9
Number('foo')     // NaN
Number('100a')    // NaN

Upvotes: 2

Akash Rao
Akash Rao

Reputation: 928

You are comparing string.

 var xxx = 112.77;
  alert(xxx);
  if(xxx < 2.50)
  {
      alert("false");     
  }
  else
  {
      alert("true");          
  }

Upvotes: 0

Related Questions