sign-bit
v1.0.4
Published
Correctly returns the sign bit of a IEEE-754 number as 1 or -1, including +/-0
Downloads
26
Maintainers
Readme
sign-bit
Correctly returns the sign bit of a IEEE-754 number as 1 or -1, including +/-0.
In IEEE-754, zeros are signed. In Javascript, numbers follow the IEEE-754 spec. Math.sign
tries to behave like the sign function in math, but returns IEEE-754 signed zeros: tc39.github.io/ecma262/#sec-math.sign. Signed zeros are tricky do detect and work with in JS. Arguably, signed zeros and the mathematical definition of the sign
don't exactly line up and there is room for confusion and ambiguity as to what the Math.sign is supposed to do in this context.
sign-bit
unambiguously returns the sign bit as 1
or -1
of all Numbers in JS, including signed zeros.
Install
npm install sign-bit
Usage
var sign = require('sign-bit')
sign(3) // 1
sign(-3) // -1
sign(0) // 1
sign(-0) // -1
Math.sign(3) // 1
Math.sign(-3) // -1
Math.sign(0) // 0
Math.sign(-0) // -0
// ¯\_(ツ)_/¯
Why?
See this thread: https://twitter.com/ydkjs/status/682225267276812288
In retrospect, I think ydkjs is wrong on the confusion here.
Contributing
Contributions welcome! Please read the contributing guidelines first.
References / Credits
- Inspired by @YDKJS's tweet
- and the accompanying fixyFill
- mathworld.wolfram.com/Sign
- tc39.github.io/ecma262/#sec-math.sign
- en.wikipedia.org/wiki/Signed_zero
- en.wikipedia.org/wiki/One-sided_limit
- en.wikipedia.org/wiki/IEEE_754-1985#Zero