LoginSignup
32
28

More than 5 years have passed since last update.

JavaScript で +0 と -0 を判別する

Last updated at Posted at 2015-03-18

データ型(JavaScript) - MSDN

正の 0 および負の 0。 JavaScript では、正のゼロと負のゼロが区別されます。

と、言いつつ +0 と -0 は区別されていないように見えますが、

+0 === -0; // true

内部では区別されていて 浮動小数点 の符号部をチェックすることで判別可能で、

function isNegativeZero(x) {
  return x === 0 && new Uint8Array(new Float32Array([ x ]).buffer)[3] === 128;
}

function isPositiveZero(x) {
  return x === 0 && new Uint8Array(new Float32Array([ x ]).buffer)[3] === 0;
}
isNegativeZero(+0); // false
isNegativeZero(-0); // true
isPositiveZero(+0); // true
isPositiveZero(-0); // false

テストで雑に deepEqual したときにエラーで弾かれる場合があります。

assert.deepEqual(new Float32Array([ +0 ]), new Float32Array([ -0 ]));
// ↑ テストに失敗する
32
28
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
28