Versions

no-loss-of-precision

Disallow literal numbers that lose precision

Recommended

The "extends": "eslint:recommended" property in a configuration file enables this rule

这条规则将不允许使用在运行时由于 64 位浮点四舍五入而在转换为 JS Number 时失去精度的数字字面。

规则细节

在 JS 中,根据 IEEE 754 标准Number 被存储为双精度浮点数字。正因为如此,数字只能保持一定数量的精度。如果程序员输入额外的数字,这些数字将在转换为 Number 类型的过程中丢失,并会导致意外行为。

使用此规则的错误示例:

Open in Playground
/*eslint no-loss-of-precision: "error"*/

const a = 9007199254740993
const b = 5123000000000000000000000000001
const c = 1230000000000000000000000.0
const d = .1230000000000000000000000
const e = 0X20000000000001
const f = 0X2_000000000_0001;

使用此规则的正确示例:

Open in Playground
/*eslint no-loss-of-precision: "error"*/

const a = 12345
const b = 123.456
const c = 123e34
const d = 12300000000000000000000000
const e = 0x1FFFFFFFFFFFFF
const f = 9007199254740991
const g = 9007_1992547409_91

Version

This rule was introduced in ESLint v7.1.0.

Resources

更改语言