Skip to content

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 truncations.

/* eslint math/prefer-math-trunc: 'error' */ /* ✓ GOOD */ x = Math.trunc(n); /* ✗ BAD */ x = n >= 0 ? Math.floor(n) : Math.ceil(n); x = ~~n; // Same as `Math.trunc(n)` if `-(2 ** 31) - 1 < n < (2 ** 31)`. x = n & -1; // Same as `Math.trunc(n)` if `-(2 ** 31) - 1 < n < (2 ** 31)`. x = n | 0; // Same as `Math.trunc(n)` if `-(2 ** 31) - 1 < n < (2 ** 31)`. x = n ^ 0; // Same as `Math.trunc(n)` if `-(2 ** 31) - 1 < n < (2 ** 31)`. x = n >> 0; // Same as `Math.trunc(n)` if `-(2 ** 31) - 1 < n < (2 ** 31)`. if (n >= 0) { x = Math.floor(n); } else { x = Math.ceil(n); }
Now loading...

🔧 Options

json
{
  "math/prefer-math-trunc": [
    "error",
    {
      "reportBitwise": true // false
    }
  ]
}
  • reportBitwise ... If true, the rule reports bitwise operations that are equivalent to Math.trunc(). Defaults to true.

📚 Further reading

🚀 Version

This rule was introduced in eslint-plugin-math v0.1.0

🔍 Implementation