math/prefer-math-trunc
enforce the use of Math.trunc() instead of other truncations
- ⚙️ This rule is included in
"plugin:math/recommended"
. - 🔧 The
--fix
option on the command line can automatically fix some of the problems reported by this rule. - 💡 Some problems reported by this rule are manually fixable by editor suggestions.
📖 Rule Details
This rule aims to enforce the use of Math.trunc()
instead of other truncation methods for removing the fractional part of numbers.
Math.trunc()
provides several advantages over alternative approaches:
- Clarity of intent: Immediately obvious that you're truncating to an integer
- Simplicity: Single function call instead of conditional logic
- Consistency: Standardized approach across all numeric ranges
- Performance: Optimized native implementation
- Reliability: Works correctly with all finite numbers, including very large values
🔧 Options
json
{
"math/prefer-math-trunc": [
"error",
{
"reportBitwise": true // false
}
]
}
reportBitwise
... Iftrue
, the rule reports bitwise operations that are equivalent toMath.trunc()
. Defaults totrue
.
reportBitwise
(boolean)
- Default:
true
- Description: Controls whether the rule reports bitwise operations that can be replaced with
Math.trunc()
When true
, the rule will flag bitwise operations like:
~~x
(double bitwise NOT)x | 0
(bitwise OR with zero)x >> 0
(right shift by zero)x << 0
(left shift by zero)x ^ 0
(bitwise XOR with zero)
When false
, the rule only reports conditional expressions and other non-bitwise patterns.
Why Bitwise Operations Are Problematic
While bitwise operations can truncate numbers, they have significant limitations:
- Limited range: Only work correctly for 32-bit signed integers (approximately ±2.1 billion)
- Unexpected behavior: Large numbers get converted to different values
- Poor readability: Intent is not immediately clear
- Platform dependency: Behavior may vary across JavaScript engines
js
// Demonstrating bitwise operation limitations
const largeNumber = 3000000000;
Math.trunc(largeNumber); // 3000000000 (correct)
~~largeNumber; // -1294967296 (wrong! 32-bit overflow)
largeNumber | 0; // -1294967296 (wrong! 32-bit overflow)
📚 Further reading
- MDN - Math.trunc()
- MDN - Math.floor()
- MDN - Math.ceil()
- MDN - Bitwise NOT (
~
) - MDN - Bitwise AND (
&
) - MDN - Bitwise OR (
|
) - MDN - Bitwise XOR (
^
) - MDN - Right shift (
>>
)
🚀 Version
This rule was introduced in eslint-plugin-math v0.1.0