Math.sign and Math.abs Keep Negatives Honest
Classify and normalize numbers with Math.sign and Math.abs: sign preserves -0 as -0, abs collapses it to 0, and both propagate NaN untouched.
Code
const values = [5, -3, 0, -0, NaN, Infinity, -Infinity];
for (const v of values) {
console.log(v, "sign:", Math.sign(v), "abs:", Math.abs(v));
}
// Math.sign 区分 -0 与 0:-0 返回 -0,0 返回 0
console.log("sign(-0):", Math.sign(-0) === -0);
// Math.abs 对 -0 返回 0:消除负零
console.log("abs(-0):", Math.abs(-0) === 0);
// Math.abs 对 NaN 仍是 NaN,不会变 0
console.log("abs(NaN):", Number.isNaN(Math.abs(NaN)));
// 经典用途:取绝对差值
function delta(a, b) {
return Math.abs(a - b);
}
console.log("delta:", delta(10, 3), delta(-5, 5));Output
Captured from a sandboxed run of this snippet in the build pipeline.
5 sign: 1 abs: 5
-3 sign: -1 abs: 3
0 sign: 0 abs: 0
-0 sign: -0 abs: 0
NaN sign: NaN abs: NaN
Infinity sign: 1 abs: Infinity
-Infinity sign: -1 abs: Infinity
sign(-0): true
abs(-0): true
abs(NaN): true
delta: 7 10Inside the snippet
Math.sign and Math.abs Keep Negatives Honest comes down to the function delta.
A single loop drives the file — for (const v of values).
Caveats
- It is dependency-free in the strict sense — the import list, if any, is empty of packages.
Using it
The one function declared in the file is function delta(a, b)
Expect labeled output — sign(-0):, abs(-0):, abs(NaN): — when the file runs.
Key statements
return Math.abs(a - b);
Interactive Tools for This Topic
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Roman Numeral ConverterConvert integers between 1 and 3999 to Roman numerals and back, rejecting malformed numeral forms.
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `delta` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.