π Prefer Math.trunc() for truncating numbers.
πΌ This rule is enabled in the following configs: β
recommended, βοΈ unopinionated.
π‘ This rule is manually fixable by editor suggestions.
Enforces a convention of using Math.trunc() instead of less clear truncation patterns.
It prevents the use of the following patterns:
x | 0(bitwise ORwith 0)~~x(twobitwise NOT)x >> 0(Signed Right Shiftwith 0)x << 0(Left Shiftwith 0)x ^ 0(bitwise XORwith 0)parseInt(String(x), 10)Number.parseInt(String(x), 10)
These patterns help truncate numbers but they are not clear and do not work in some cases. For example, parseInt(String(x), 10) can produce unexpected results for very large or very small numbers that stringify to exponential notation.
None of these patterns is exactly equivalent to Math.trunc(x), so the rule only offers suggestions. The bitwise patterns convert the value to a 32-bit integer, so they wrap values outside that range and turn NaN into 0 (~~(2 ** 32) is 0, while Math.trunc(2 ** 32) is 4294967296). There is no suggestion for an assignment whose left-hand side has a side effect, or when a comment would be lost.
const foo = 37.4;
// β
console.log(foo | 0);
// β
console.log(~~foo);
// β
console.log(foo << 0);
// β
console.log(foo >> 0);
// β
console.log(foo.bar ^ 0);
// β
console.log(parseInt(String(foo), 10));
// β
console.log(Number.parseInt(String(foo), 10));
// β
console.log(Math.trunc(foo));let foo = 37.4;
// β
foo |= 0;
// β
foo = Math.trunc(foo);// β
const foo = 37.4;
console.log(foo | 3);// β
const foo = 37.4;
console.log(~foo);// β
const foo = 37.4;
console.log(foo >> 3);// β
const foo = 37.4;
console.log(foo << 3);// β
const foo = 37.4;
console.log(foo ^ 3);