The JavaScript Math.sign()
method only works on the number primitive values, and not on the bigint primitive values:
// TypeError: Cannot convert a BigInt value to a number
Math.sign(2n);
Therefore, you can implement a custom "sign" method for bigint numbers instead, which would return similar values to the Math.sign()
method, i.e.:
- Return
0
if value is0
; - Return
-0
if value is-0
; - Return
1
if value is greater than0
; - Return
-1
if value is less than0
.
You can implement this for bigint numbers in the following way:
// ES10+ const sign = (val) => { if (val === 0n) { return val; } return (val < 0n) ? -1n : 1n; };
Please note that if the value is -0n
, then 0n
is returned (instead of -0n
). This is due to the way browsers handle the -0n
as a return value.
For example, you could use the custom sign
function (with bigint values) in the following way:
console.log(sign(0n)); // 0n console.log(sign(-0n)); // 0n console.log(sign(10n)); // 1n console.log(sign(-10n)); // -1n
console.log(sign(18014398509481982n)); // 1n console.log(sign(-18014398509481982n)); // -1n
console.log(sign(BigInt(Number.MAX_SAFE_INTEGER))); // 1n console.log(sign(BigInt(-Number.MAX_SAFE_INTEGER))); // -1n
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.