示例工程 02-values-types-equality

另有 1 个文件未随站点发布(平台工程、二进制或超过 200KB)。

02-values-types-equality/04-number-precision-bigint/main.js

javascript · 1.8 KB

运行:02 · 浮点精度与 BigInt

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// main.js —— Number 的精度与 BigInt
// 浮点误差不是「JS 的 bug」,是 IEEE-754 binary64 的固有性质。
 
export function checks() {
  const rows = [];
  const add = (label, value) => rows.push({ label, value: String(value), raw: value });
  const addThrows = (label, fn) => {
    try {
      fn();
      rows.push({ label, value: '没有抛错', raw: undefined });
    } catch (e) {
      rows.push({ label, value: `${e.constructor.name}`, raw: e.constructor.name });
    }
  };
 
  add('0.1 + 0.2 === 0.3', 0.1 + 0.2 === 0.3);
  add('(0.1 + 0.2).toFixed(20)', (0.1 + 0.2).toFixed(20));
  add('Number.EPSILON === 2 ** -52', Number.EPSILON === 2 ** -52);
  add('Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON', Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
 
  add('Number.MAX_SAFE_INTEGER', Number.MAX_SAFE_INTEGER);
  add('2 ** 53 === 2 ** 53 + 1', 2 ** 53 === 2 ** 53 + 1);
  add('9007199254740993 === 9007199254740992', 9007199254740993 === 9007199254740992);
  add("BigInt('9007199254740993')", BigInt('9007199254740993'));
  add('(1e21).toString()', (1e21).toString());
 
  add('typeof 1n', typeof 1n);
  add('1n === 1', 1n === 1);
  add('1n == 1', 1n == 1);
  add('1n < 2', 1n < 2);
  add('7n / 2n(向零截断)', 7n / 2n);
  add('-7n / 2n', -7n / 2n);
  add('Number(1n)', Number(1n));
 
  addThrows('1n + 1(不能混算)', () => 1n + 1);
  addThrows('BigInt(1.5)(不接受非整数)', () => BigInt(1.5));
  addThrows('JSON.stringify(1n)', () => JSON.stringify(1n));
 
  return rows;
}
 
export function run(log = console.log) {
  const rows = checks();
  log('表达式 => 结果');
  for (const r of rows) log(`${r.label} => ${r.value}`);
  log('-'.repeat(64));
  log('要点:Number 是 IEEE-754 binary64,只有 53 位有效整数精度;需要精确大整数时用 BigInt(字面量以 n 结尾)。');
  return rows;
}