JavaScript Math.trunc 与 Math.floor:负零、数值转换和 32 位陷阱
给一个数“去掉小数”,究竟是在保留运动方向、寻找它所在的区间,还是把它写进固定宽度字段?这三个需求很容易被写成同一行代码,却有不同的边界。正数上的几次试算不足以说明 Math.trunc、Math.floor 与位运算可以互换;真正暴露差异的通常是负数、负零和超出 32 位范围的数据。
本文先约定输入与输出,再给出三个可以单独复制运行的小例子。范围仅限 JavaScript 的 Number 语义及明确列出的转换行为,不讨论性能排名,也不提供万能的数值清洗器。

一、先区分四种输出契约
Math.trunc 的有限数值结果朝零靠近:3.75 得到 3,-3.75 得到 -3。Math.floor 则寻找不大于输入的最大整数,因此 -3.75 得到 -4。两者对正小数表现相同,对负小数往往相差一。不要把“向下取整”当成“删除小数部分”的同义词。依据:TC39 Math.trunc 与 TC39 Math.floor。
对 Number 使用 x | 0 或 ~~x,会进入有符号 32 位整数语义,结果范围是 -2147483648 到 2147483647;x >>> 0 得到无符号 32 位结果,范围是 0 到 4294967295。超出范围不是报错或钳制,而是截断后按模 2 的 32 次方折回,再按需要解释符号。2147483648.75 经 Math.trunc 得到 2147483648,经 x | 0 却变成 -2147483648。负数使用无符号右移还会变成很大的正数。依据:ToInt32、ToUint32 和 ToFixedSizeInteger。
这些区别意味着:如果业务只想去掉小数,用 Math.trunc 表达意图;如果业务本来就是固定宽度位操作,再选择位运算。不能只因为写法短,就把范围检查省掉。MDN 也明确指出,位运算技巧不是 Math.trunc 的等价替代。参见 MDN Math.trunc。
二、负零、非有限值与隐式转换
Math.trunc(-0.75) 返回 -0,传入 -0 也保留 -0。负零通常不会改变普通计数显示,但倒数会暴露其符号:1 除以 -0 得到 -Infinity。需要检查这类边界时用 Object.is,而不要只看格式化字符串。下文所有数值断言都保留 -0 与 NaN 的可区分性。若界面明确不需要负零,可以在业务边界主动将它规范成 0,但这已经是额外规则。
Math.trunc(NaN) 仍是 NaN,正负 Infinity 仍保留;上述 Number 位运算却把这些值变为 0。这种“看起来正常”的零可能掩盖上游缺失值,尤其不能用 Math.trunc(x) || 0 冒充验证。原生函数没有替你判断数据是否有效。相关特殊值规则见 TC39 算法。
另一个常见误区是把截断当成十进制文本解析。Math.trunc 会先做 ToNumber:数字字符串可以转换,空字符串和 null 可变成 0,带单位的“12px”则得到 NaN;“1e3”和“0x10”也属于可接受的数值形式。BigInt 与 Symbol 会抛 TypeError,对象则可能执行其转换钩子。把 Number(x) 加在前面还会扩大可接受类型,例如 Number(1n) 可以产生 1,但 Math.trunc(1n) 本身不接受 BigInt。依据:ToNumber。
parseInt 的任务是按进制读取字符串前缀,故 parseInt("12px", 10) 能得到 12;把数字 1e-7 交给它,会先形成指数形式的字符串,最后得到 1,而不是截断应有的 0。如果表单只允许普通十进制文本,应先定义文本语法,而不是让几个转换函数互相兜底。参见 MDN parseInt。
三、例子 1:整步位移与所在网格不能混用
假设单位长度为一。问“已经完成多少个整步位移”时,-3.75 保留方向后得到 -3;问“坐标落在哪个左闭右开的单位区间”时,它落在 [-4, -3),编号应为 -4。下面刻意返回两项,让调用者看见不同问题的答案。输入限定为 Number、有限且绝对值不超过一百万,避免把字符串转换或异常量级偷偷纳入运动逻辑。保留 -0 是这个例子的明确选择。
console.log("strict-this=" + (function () { return this === undefined; })());
function motion(value) {
if (typeof value !== "number") throw new TypeError("Number required");
if (!Number.isFinite(value) || Math.abs(value) > 1000000) {
throw new RangeError("Outside motion range");
}
return [Math.trunc(value), Math.floor(value)];
}
function check(run, expected, label) {
let value;
let error;
try { value = run(); } catch (caught) { error = caught; }
if (typeof expected === "function") {
if (!(error instanceof expected)) throw new Error(label + ": wrong exception");
} else {
if (error) throw error;
if (!Object.is(value, expected)) throw new Error(label + ": wrong value");
}
}
const result1 = motion(3.75);
check(() => result1[0], 3, "motion 1.0");
check(() => result1[1], 3, "motion 1.1");
const result2 = motion(-3.75);
check(() => result2[0], -3, "motion 2.0");
check(() => result2[1], -4, "motion 2.1");
const result3 = motion(-0.75);
check(() => result3[0], -0, "motion 3.0");
check(() => result3[1], -1, "motion 3.1");
const result4 = motion(-0);
check(() => result4[0], -0, "motion 4.0");
check(() => result4[1], -0, "motion 4.1");
check(() => motion("3.75"), TypeError, "motion 5");
check(() => motion(Infinity), RangeError, "motion 6");
check(() => motion(1000001), RangeError, "motion 7");
console.log("motion: 7 cases passed");普通模式输出:
strict-this=false motion: 7 cases passed
四、例子 2:十进制输入框,先解析再截断
这个输入框接受可选正负号、整数和小数,允许前后空白;不接受指数、十六进制、单位后缀或空白内容。它的语法比原生 ToNumber 更窄,这是产品约束,不是宣称 JavaScript 的其他格式无效。范围仍限定为正负一百万,最后为显示目的把 -0 转成 0。注意正则负责格式,Number 负责表示转换,Math.trunc 负责截断,三个步骤各有职责。
console.log("strict-this=" + (function () { return this === undefined; })());
function decimalField(text) {
if (typeof text !== "string") throw new TypeError("Text required");
const cleaned = text.trim();
if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(cleaned)) {
throw new SyntaxError("Plain decimal required");
}
const value = Number(cleaned);
if (!Number.isFinite(value) || Math.abs(value) > 1000000) {
throw new RangeError("Outside field range");
}
const result = Math.trunc(value);
return Object.is(result, -0) ? 0 : result;
}
function check(run, expected, label) {
let value;
let error;
try { value = run(); } catch (caught) { error = caught; }
if (typeof expected === "function") {
if (!(error instanceof expected)) throw new Error(label + ": wrong exception");
} else {
if (error) throw error;
if (!Object.is(value, expected)) throw new Error(label + ": wrong value");
}
}
check(() => decimalField(" -3.75 "), -3, "decimalField 1");
check(() => decimalField("-.75"), 0, "decimalField 2");
check(() => decimalField("12."), 12, "decimalField 3");
check(() => decimalField("+4.5"), 4, "decimalField 4");
check(() => decimalField(""), SyntaxError, "decimalField 5");
check(() => decimalField("1e3"), SyntaxError, "decimalField 6");
check(() => decimalField("0x10"), SyntaxError, "decimalField 7");
check(() => decimalField("12px"), SyntaxError, "decimalField 8");
check(() => decimalField("1000001"), RangeError, "decimalField 9");
check(() => decimalField(null), TypeError, "decimalField 10");
console.log("decimalField: 10 cases passed");普通模式输出:
strict-this=false decimalField: 10 cases passed
五、例子 3:32 位协议字段,拒绝而不是折回
如果接口契约要求一个有符号 32 位整数,静默把 2147483648 变成负数通常不合适。下面的函数既不截断小数,也不允许隐式字符串转换:只有已经是整数的 Number 才进入范围判断。它只是一个字段验证例子,不执行网络请求、不分配缓冲区,也不决定真实协议的字节序。这里同样明确把 -0 规范成 0。
console.log("strict-this=" + (function () { return this === undefined; })());
function int32Field(value) {
if (!Number.isInteger(value)) throw new TypeError("Integer Number required");
if (value < -2147483648 || value > 2147483647) {
throw new RangeError("Outside signed 32-bit range");
}
return Object.is(value, -0) ? 0 : value;
}
function check(run, expected, label) {
let value;
let error;
try { value = run(); } catch (caught) { error = caught; }
if (typeof expected === "function") {
if (!(error instanceof expected)) throw new Error(label + ": wrong exception");
} else {
if (error) throw error;
if (!Object.is(value, expected)) throw new Error(label + ": wrong value");
}
}
check(() => int32Field(2147483647), 2147483647, "int32Field 1");
check(() => int32Field(-2147483648), -2147483648, "int32Field 2");
check(() => int32Field(-0), 0, "int32Field 3");
check(() => int32Field(3.75), TypeError, "int32Field 4");
check(() => int32Field(NaN), TypeError, "int32Field 5");
check(() => int32Field(Infinity), TypeError, "int32Field 6");
check(() => int32Field("12"), TypeError, "int32Field 7");
check(() => int32Field(1n), TypeError, "int32Field 8");
check(() => int32Field(2147483648), RangeError, "int32Field 9");
check(() => int32Field(-2147483649), RangeError, "int32Field 10");
console.log("int32Field: 10 cases passed");普通模式输出:
strict-this=false int32Field: 10 cases passed
六、32 个输入,把转换差异写成固定测试
下面每一行的四个期望值依次对应 Math.trunc、Math.floor、x | 0 和 x >>> 0。TypeError 表示必须抛出该类型异常;其余值使用 Object.is 比较。对象和数组每次调用都会重新构造,防止一次转换的状态污染下一次操作。期望值事先固定,不会拿某个待测函数的结果当另一个函数的“答案”。
console.log("strict-this=" + (function () { return this === undefined; })());
function check(run, expected, label) {
let value;
let error;
try { value = run(); } catch (caught) { error = caught; }
if (typeof expected === "function") {
if (!(error instanceof expected)) throw new Error(label + ": wrong exception");
} else {
if (error) throw error;
if (!Object.is(value, expected)) throw new Error(label + ": wrong value");
}
}
const cases = [
["positive fraction", () => 3.75, 3, 3, 3, 3],
["negative fraction", () => -3.75, -3, -4, -3, 4294967293],
["positive below one", () => 0.75, 0, 0, 0, 0],
["negative below one", () => -0.75, -0, -1, 0, 0],
["positive zero", () => 0, 0, 0, 0, 0],
["negative zero", () => -0, -0, -0, 0, 0],
["positive integer", () => 12, 12, 12, 12, 12],
["negative integer", () => -12, -12, -12, -12, 4294967284],
["NaN", () => NaN, NaN, NaN, 0, 0],
["positive infinity", () => Infinity, Infinity, Infinity, 0, 0],
["negative infinity", () => -Infinity, -Infinity, -Infinity, 0, 0],
["trimmed numeric string", () => " -3.75 ", -3, -4, -3, 4294967293],
["empty string", () => "", 0, 0, 0, 0],
["whitespace string", () => " ", 0, 0, 0, 0],
["null", () => null, 0, 0, 0, 0],
["true", () => true, 1, 1, 1, 1],
["false", () => false, 0, 0, 0, 0],
["undefined", () => undefined, NaN, NaN, 0, 0],
["unit suffix", () => "12px", NaN, NaN, 0, 0],
["exponent string", () => "1e3", 1000, 1000, 1000, 1000],
["hex string", () => "0x10", 16, 16, 16, 16],
["near signed maximum", () => 2147483647.75, 2147483647, 2147483647, 2147483647, 2147483647],
["above signed maximum", () => 2147483648.75, 2147483648, 2147483648, -2147483648, 2147483648],
["below signed minimum fraction", () => -2147483648.75, -2147483648, -2147483649, -2147483648, 2147483648],
["below signed minimum integer", () => -2147483649, -2147483649, -2147483649, 2147483647, 2147483647],
["positive wrap", () => 4294967296.75, 4294967296, 4294967296, 0, 0],
["negative wrap", () => -4294967296.75, -4294967296, -4294967297, 0, 0],
["empty array", () => [], 0, 0, 0, 0],
["singleton array", () => [2.75], 2, 2, 2, 2],
["valueOf object", () => ({ valueOf() { return -2.75; } }), -2, -3, -2, 4294967294],
["BigInt", () => 1n, TypeError, TypeError, TypeError, TypeError],
["Symbol", () => Symbol('x'), TypeError, TypeError, TypeError, TypeError],
];
const operations = [Math.trunc, Math.floor, x => x | 0, x => x >>> 0];
for (const [label, makeInput, ...expected] of cases) {
operations.forEach((operation, index) => {
check(() => operation(makeInput()), expected[index], label + " / " + index);
});
}
console.log("native: 32 cases, 128 assertions passed");普通模式输出:
strict-this=false native: 32 cases, 128 assertions passed
七、用八个反例识别错误替换
下面的 wrong 函数都是用于展示差异的反例,不是推荐实现。每一行同时检查原生结果与错误包装的实际结果,然后确认两套预期确实不同。除了负数和越界,还覆盖了负零丢失、指数文本、Infinity、BigInt 类型边界和 NaN 被默认值吞掉的问题。这种小规模反例集很适合在迁移旧代码前,检查曾经依赖的“简写”到底承诺了什么。
console.log("strict-this=" + (function () { return this === undefined; })());
function check(run, expected, label) {
let value;
let error;
try { value = run(); } catch (caught) { error = caught; }
if (typeof expected === "function") {
if (!(error instanceof expected)) throw new Error(label + ": wrong exception");
} else {
if (error) throw error;
if (!Object.is(value, expected)) throw new Error(label + ": wrong value");
}
}
const witnesses = [
["floor", () => -3.75, x => Math.floor(x), -3, -4],
["signed32", () => 2147483648.75, x => x | 0, 2147483648, -2147483648],
["double NOT", () => -0.75, x => ~~x, -0, 0],
["unsigned32", () => -1.75, x => x >>> 0, -1, 4294967295],
["parse decimal prefix", () => 1e-7, x => parseInt(x, 10), 0, 1],
["subtract remainder", () => Infinity, x => x - x % 1, Infinity, NaN],
["explicit Number broadens BigInt", () => 1n, x => Math.trunc(Number(x)), TypeError, 1],
["falsy fallback", () => NaN, x => Math.trunc(x) || 0, NaN, 0],
];
for (const [label, makeInput, wrong, goodExpected, wrongExpected] of witnesses) {
check(() => Math.trunc(makeInput()), goodExpected, label + " native");
check(() => wrong(makeInput()), wrongExpected, label + " incorrect wrapper");
if (Object.is(goodExpected, wrongExpected)) throw new Error("Invalid witness");
}
check(() => Number.isInteger(Math.trunc(9007199254740992)), true, "integral");
check(() => Number.isSafeInteger(Math.trunc(9007199254740992)), false, "safe");
check(() => 0.1 + 0.2 === 0.3, false, "binary fraction");
check(() => Object.is(Math.trunc(-0.75), -0), true, "negative zero");
check(() => 1 / Math.trunc(-0.75), -Infinity, "negative reciprocal");
check(() => ~~1n, 1n, "BigInt NOT is not Number truncation");
let calls = 0;
const input = { valueOf() { calls += 1; return -2.75; } };
check(() => Math.trunc(input), -2, "coercion result");
check(() => calls, 1, "coercion count");
check(() => parseInt("12px", 10), 12, "prefix parsing");
check(() => Math.trunc("12px"), NaN, "whole numeric conversion");
console.log("witnesses: 8 mismatches confirmed; 10 probes passed");普通模式输出:
strict-this=false witnesses: 8 mismatches confirmed; 10 probes passed
八、整数值、安全整数与精度是三回事
Math.trunc 返回 Number,不会把数据升级成任意精度整数。9007199254740992 是可表示的整数值,Number.isInteger 为 true,但已经不属于安全整数范围,因此 Number.isSafeInteger 为 false。安全整数的边界是正负 9007199254740991;若原始输入在转换成 Number 时已经丢失信息,后续截断不能还原。参见 MDN Number.isSafeInteger。
同样,截断不会修复二进制浮点对十进制小数的表示误差。0.1 与 0.2 的相加结果不精确等于 0.3,任意加一个常量再取整也不是通用修复。应该先决定数据的表示、量级和误差契约;本教程的十进制输入例子只保证语法与范围,不保证任意长度小数的精确表示。关于该限制可查看 MDN Number.EPSILON 的数值表示说明。
本文五段可执行代码已在 Node.js v24.19.0 中逐段验证,普通模式和真实词法严格模式都通过。严格模式验证时将完整源代码重新交给 Function 构造器,并在函数体开头放入 "use strict";每段首行的 this 探针从 false 变为 true,其余输出保持一致。上面的输出框展示普通模式结果。复制时每个代码框应单独执行,输出框不属于程序。
测试范围是 32 个原生输入、8 个错误包装反例、10 个边界探针和三个例子的 27 个输入。它没有覆盖所有对象转换副作用、所有浮点值或所有浏览器,也没有测量性能。实际选型可以按三步判断:先确定允许什么输入,再决定取整方向,最后明确负零、非有限值和范围越界如何处理。

