sTg
sTg

Reputation: 4424

Javascript - Identifying Positive 0 and negative 0 numbers

I have a requirement where i have to identify if the number is a positive 0 or a negative 0 and do color coding for those numbers. This is applicable only for 0s and not greater or lesser than 0.

i.e.:

  1. 0.00000983 (Positive Zero)

  2. -0.0000343 (Negative Zero)

I tried below method but this does not help for values having decimals with 0. Please guide.

function isMinusZero(value) {
  return 1/value === -Infinity;
}

isMinusZero(0); // false
isMinusZero(-0); // true

Upvotes: 2

Views: 832

Answers (5)

lealceldeiro
lealceldeiro

Reputation: 14958

Here is an alternative:

function isMinusZero(value) {
  if (Object.is(value, -0)) return true;   // handles OP's specific requirement
  if (value === 0) return false;
  return 1/Math.abs(Math.ceil(value)) === Infinity;
}

console.log(isMinusZero(1234)); // false
console.log(isMinusZero(-1223)); // false
console.log(isMinusZero(0)); // false
console.log(isMinusZero(-0)); // true
console.log(isMinusZero(0.0000000000000000000000000000000000000000976767)); // false
console.log(isMinusZero(-0.0000000000000000000000000000000000000000967676767)); // true
console.log(isMinusZero(-0.0000000000003400003400000000000000034000000000967676767)); // true

References:

Upvotes: 2

ABlue
ABlue

Reputation: 673

you can use Math.sign()

function isZeroSign(value){

return   Math.sign(value) > 0 ;

}

console.log(isZeroSign(0.00022));
console.log(isZeroSign(-0.0033));
console.log(isZeroSign(5500));
console.log(isZeroSign(-0.000000000000000000000000041))

Upvotes: 0

Ogreucha
Ogreucha

Reputation: 688

Another solution using Object.is:

function isMinusZero(value) {
  return Object.is(-0, value);
}

console.log(
  isMinusZero(0), // false
  isMinusZero(-0) // true
)

Upvotes: 1

User863
User863

Reputation: 20039

You are searching for Math.sign()

  • If the argument is positive, returns 1.
  • If the argument is negative, returns -1.
  • If the argument is positive zero, returns 0.
  • If the argument is negative zero, returns -0.
  • Otherwise, NaN is returned.

Upvotes: 1

Ankur Patel
Ankur Patel

Reputation: 488

Here is your solution

function isMinusZero(value) {
  return value.toString().startsWith("-");
}
console.log(
  isMinusZero(0), // false
  isMinusZero(-0) // true
)

.

Upvotes: -3

Related Questions