AddyProg
AddyProg

Reputation: 3050

Why "1.0" is not equal to "+1.0" in JavaScript?

I am doing a simple comparison in JavaScript but its not working. Here is the script

var value = '1.0';
var minLimit = '+0.5';
var maxLimit = '+999';
if (value >= minLimit && value <= maxLimit) {
    console.log(value);
}
else
{
 console.log('not matched');
}

Is there anything I am missing comparison ? Here is the fiddle http://jsfiddle.net/9ouwkyyt/

Upvotes: 2

Views: 337

Answers (3)

SULFIKAR A N
SULFIKAR A N

Reputation: 446

You only compare string, since if you want compare in integer format convert result into integer.

var value = '1.0';
    var minLimit = '+0.5';
    var maxLimit = '+999';
    if (parseInt(value )>= parseInt(minLimit) && parseInt(value )<= parseInt(maxLimit)) {
        console.log(value);
    }
    else
    {
     console.log('not matched');
    }

Upvotes: 0

Rik_S
Rik_S

Reputation: 381

There is a diffirence between '+999' and +999.

The one with quotes is a string, whereas the one without is a integer value. What you want to do is numeric comparison, not string comparison.

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388406

it is because you are doing a string comparison, not a numeric value comparison.

Convert the values to numeric values - you can use a unary plus, Number() or parseFloat() based on your need

var value = +'1.0';
var minLimit = +'+0.5';
var maxLimit = +'+999';
if (value >= minLimit && value <= maxLimit) {
  console.log(value);
} else {
  console.log('not matched');
}

Upvotes: 7

Related Questions