Languages
[Edit]
EN

JavaScript - how to check is zero positive (+0) or negative (-0)?

7 points
Created by:
Root-ssh
68500

Using JavaScript it is possible to check if zero is positive or negative in following way.

1. Positive / negative zero test example

// ONLINE-RUNNER:browser;

console.log(      0 ==  0     ); // true
console.log(     -0 == -0     ); // true
console.log(     -0 == +0     ); // true

console.log( 1 / +0 == 1 / +0 ); // true
console.log( 1 / -0 == 1 / -0 ); // true
console.log( 1 / -0 == 1 / +0 ); // <--- false

console.log(      0 ===      0 ); // true
console.log(     -0 ===     -0 ); // true
console.log(     -0 ===     +0 ); // true

console.log( 1 / +0 === 1 / +0 ); // true
console.log( 1 / -0 === 1 / -0 ); // true
console.log( 1 / -0 === 1 / +0 ); // <--- false

Explaination: typical programmer do not think about kind of zero. To avoid computation mistakes JavaScript returns true during -0 and +0 comparision. In practise sommteims it is neccessary to make more complicated computation that requires more precised results like close to 0 on left or right site of axis (OX axis). This is reasone why -0 and +0 have been intorduced - it gives information how 0 has been computed. The way how to check if zero is positive or negative is based on some trick: 1 / -0 = -Inf; 1 / +0 = +Inf; -Inf != +Inf; +Inf = +Inf; -Inf = -Inf;

2. Alternative way to make zero test example

// ONLINE-RUNNER:browser;

console.log( Object.is(  0,  0 ) ); // true
console.log( Object.is( -0, -0 ) ); // true
console.log( Object.is( -0, +0 ) ); // false

Note: this approach has been introduced in ECMAScript 2015 (ES6).

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join