Number.EPSILON

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 2015 年 9 月以来,该特性已在各大浏览器中可用。

Number.EPSILON 静态数据属性表示 1 与大于 1 的最小浮点数之间的差值。

试一试

const result = Math.abs(0.2 - 0.3 + 0.1);

console.log(result);
// Expected output: 2.7755575615628914e-17

console.log(result < Number.EPSILON);
// Expected output: true

2-52,或约等于 2.2204460492503130808472633361816E-16

Number.EPSILON 的属性特性
可写
可枚举
可配置

描述

Number.EPSILON 是 1 与 Number 格式中下一个可表示数之间的差值,因为 双精度浮点格式 只有 52 位来表示 尾数,而最低位具有 2-52 的权重。

请注意,随着数值增大,浮点数的绝对精度会降低,因为指数增长而尾数的精度保持不变。Number.MIN_VALUE 是最小的可表示正数,它远小于 Number.EPSILON

由于 EPSILONNumber 的静态属性,您始终使用 Number.EPSILON 来访问它,而不是作为数字值的属性。

示例

相等性测试

任何占用有限位数(无论您选择哪种基数,例如十进制或二进制)的数字编码系统,都必然无法精确表示所有数字,因为您试图使用有限的内存来表示数轴上的无限多个点。例如,基数为 10(十进制)的系统无法精确表示 1/3,而基数为 2(二进制)的系统无法精确表示 0.1。因此,例如,0.1 + 0.2 不会精确等于 0.3

js
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false

出于这个原因,通常建议不要使用 === 来比较浮点数。相反,如果两个数字足够接近,我们可以认为它们是相等的。当算术运算的幅度接近 1 时,Number.EPSILON 常量通常是一个合理的误差阈值,因为 EPSILON 本质上指定了数字“1”的精度。

js
function equal(x, y) {
  return Math.abs(x - y) < Number.EPSILON;
}

const x = 0.2;
const y = 0.3;
const z = 0.1;
console.log(equal(x + z, y)); // true

然而,对于任何以更大数量级进行的算术运算,Number.EPSILON 都是不合适的。如果您的数据量级在 103,则小数部分的精度将远小于 Number.EPSILON

js
function equal(x, y) {
  return Math.abs(x - y) < Number.EPSILON;
}

const x = 1000.1;
const y = 1000.2;
const z = 2000.3;
console.log(x + y); // 2000.3000000000002; error of 10^-13 instead of 10^-16
console.log(equal(x + y, z)); // false

在这种情况下,需要更大的容差。由于比较的数字幅度约为 2000,因此像 2000 * Number.EPSILON 这样的乘数会为此实例创建足够的容差。

js
function equal(x, y, tolerance = Number.EPSILON) {
  return Math.abs(x - y) < tolerance;
}

const x = 1000.1;
const y = 1000.2;
const z = 2000.3;
console.log(equal(x + y, z, 2000 * Number.EPSILON)); // true

除了幅度之外,考虑输入的精度也很重要。例如,如果数字是从表单输入收集的,并且输入值只能以 0.1 的步长进行调整(例如 <input type="number" step="0.1">),则通常允许更大的容差是有意义的,例如 0.01,因为数据只有 0.1 的精度。

注意:重要提示:不要简单地将 Number.EPSILON 用作相等性测试的阈值。应使用适合您所比较数字的幅度与精度的阈值。

规范

规范
ECMAScript® 2026 语言规范
# sec-number.epsilon

浏览器兼容性

另见