0

After ajax query I have the next numbers:

var a = "5.20";
var b = "7.20";
var c = "11.20";

I have noticed that if compare numbers above 10.00 the condition is false. I do not understand why this happens

if (b > a) console.log("higher"); // true
if (c > b) console.log("higher"); // not true

I have solved the problem with next code (it should also work parseFloat)

if ((+c) > (+b)) console.log("higher"); // true
kurtko
  • 1,978
  • 4
  • 30
  • 47

3 Answers3

3

"5" > "10" for the same reason that "m" > "ba". Strings are compared alphabetically (even if they contain digits) - or rather lexicographically.

melpomene
  • 84,125
  • 8
  • 85
  • 148
0

The variables are string type. Not integers.

typeof("5.20"); // OUTPUT: "string"

Remove the quotation marks:

var a = 5.20;
var b = 7.20;
var c = 11.20;
if (b > a) console.log("higher"); // true
if (c > b) console.log("higher"); // also true

Example: https://www.w3schools.com/js/js_comparisons.asp

Gastón Corti
  • 51
  • 1
  • 6
-1

You are comparing two strings alphabetically. If you remove the quotes where you create the variables then you will have numbers and your code will work.

var a = 5.20;
var b = 7.20;
var c = 11.20;
Bijan Rafraf
  • 393
  • 1
  • 7