14

When I try to compare two numbers using JavaScript Number() function, it returns false value for equal numbers. However, the grater-than(">") and less-than("<") operations return true.

var fn = 20;
var sn = 20;

alert(new Number(fn) === new Number(sn));

This alert returns a false value. Why is this not returns true?

2 Answers 2

21

new Number() will return object not Number and you can not compare objects like this. alert({}==={}); will return false too.

Remove new as you do not need to create new instance of Number to compare values.

var fn = 20;
var sn = 20;

alert(Number(fn) === Number(sn));

Sign up to request clarification or add additional context in comments.

Comments

2

If you are using floating numbers and if they are computed ones. Below will be a slightly more reliable way.

console.log(Number(0.1 + 0.2) == Number(0.3)); // This will return false.

To reliably/almost reliably do this you can use something like this.

const areTheNumbersAlmostEqual = (num1, num2) => {
    return Math.abs( num1 - num2 ) < Number.EPSILON;
}
console.log(areTheNumbersAlmostEqual(0.1 + 0.2, 0.3));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.