Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing equality of two numbers using JavaScript Number() function

Tags:

javascript

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?

like image 613
WC Madhubhashini Avatar asked Mar 18 '16 06:03

WC Madhubhashini


People also ask

How do I compare two numbers in JavaScript?

Javascript Equals Operators The non-strict equals operator (==) determines if two values are effectively equal regardless of their data type. The strict equals operator (===) determines if two values are exactly the same in both data type and value.

What is == and === in JavaScript?

The main difference between the == and === operator in javascript is that the == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.

What is === in JavaScript?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

Can we compare two functions in JavaScript?

This means you can test to see if your functions are exactly the same, including what spaces and newlines you put in it. But first you have to eliminate the difference in their names. function foo1() { return 1; } function foo2() { return 1; } //Get a string of the function declaration exactly as it was written.


2 Answers

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.

Try this:

var fn = 20;
var sn = 20;

alert(Number(fn) === Number(sn));
like image 166
Rayon Avatar answered Oct 05 '22 14:10

Rayon


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));
like image 26
Parash Avatar answered Oct 05 '22 13:10

Parash