is-negative-nan
v1.0.1
Published
Check Negative NaN easily
Downloads
3
Readme
Installation
Install the package using npm:
npm install is-negative-nan
Or using yarn:
yarn add is-negative-nan
Or using pnpm:
pnpm add is-negative-nan
Usage
import { isNegativeNaN } from 'is-negative-nan';
console.log(isNegativeNaN(-NaN)); // true
Why is this useful?
console.log(NaN === NaN); // false
console.log(-NaN === NaN); // false
NaN; // NaN
-NaN; // NaN
String(NaN); // 'NaN'
String(-NaN); // 'NaN'
Number.isNaN(NaN); // true
Number.isNaN(-NaN); // true
Object.is(NaN, NaN); // true
Object.is(-NaN, NaN); // true
Object.is(-NaN, -NaN); // true
Object.is(NaN, -NaN); // true
How it works?
isNegativeNaN converts the number to a Float64Array
and then to a Uint32Array
. It then checks if the number is negative by checking the 31st bit
of the Uint32Array.
export function isNegativeNaN(val: number) {
if (!Number.isNaN(val)) return false;
const f64 = new Float64Array(1);
f64[0] = val;
const u32 = new Uint32Array(f64.buffer);
const isNegative = u32[1] >>> 31 === 1;
return isNegative;
}