JavaScript 中的数字截断

2025-06-07

JavaScript 中的数字截断

SamanthaMing.com 的代码小贴士

用于Math.trunc()截断浮点数并返回其整数部分。此函数不进行任何舍入,只是删除小数点后的所有数字。现在你得到了一个整数,耶🎊

const number = 80.6

// Old Way
number < 0 ? Math.ceil(number) : Math.floor(number);
// 80

// ✅ES6 Way
const es6 = Math.trunc(number);
// 80
Enter fullscreen mode Exit fullscreen mode

例子

Math.trunc()只是截断(截去)其右边的点和数字。无论参数是正数还是负数。

Math.trunc(80.9); // 80
Math.trunc(80.8); // 80
Math.trunc(80.8); // 80
Math.trunc(80.6); // 80
Math.trunc(80.5); // 80
Math.trunc(80.4); // 80
Math.trunc(80.3); // 80
Math.trunc(80.2); // 80
Math.trunc(80.1); // 80

Math.trunc(-80.1); // -80
Enter fullscreen mode Exit fullscreen mode

现在让我们看一些带有非数字参数的例子:

Math.trunc('80.1'); // 80
Math.trunc('hello'); // NaN
Math.trunc(NaN); // NaN
Math.trunc(undefined); // NaN
Math.trunc(); // NaN
Enter fullscreen mode Exit fullscreen mode

使用数字截断parseInt

您可以使用以下方法获得类似的结果parseInt

parseInt(80.1); // 80
parseInt(-80.1); // -80

parseInt('80.1'); // 80
parseInt('hello'); // NaN
parseInt(undefined); // NaN
parseInt(); // NaN
Enter fullscreen mode Exit fullscreen mode

Math.trunc()对比parseInt()

parseInt主要用于字符串参数。因此,如果处理数字,最好使用Math.trunc()

如果您好奇,我写了一个比较这两个功能的性能测试。

jsPerf:Math.trunc 与 parseInt

陷阱parseInt

使用 时存在一个潜在问题parseInt。当你传入一个非字符串的参数(在本例中是一个数字)时,它会先使用toString()抽象操作将值转换为字符串。大多数情况下,parseInt这样做是没问题的。但让我们看一个可能并非如此的例子。

const number = 1000000000000000000000.5;

const result = parseInt(number);

console.log(result); // 1 <-- 😱
Enter fullscreen mode Exit fullscreen mode

☝️那么为什么会发生这种情况呢?那是因为我们的参数不是string,所以它做的第一件事parseInt就是将参数转换为string

const number = 1000000000000000000000.5;

const result = number.toString(); 

console.log(result); // "1e+21"
Enter fullscreen mode Exit fullscreen mode

所以当它尝试从中获取整数时1e+21,它只知道获取1值。所以,使用parseInt肯定有它的陷阱。由于这种极端情况,你可能需要考虑使用Math函数 👍

浏览器支持

大多数现代浏览器都支持Math.trunc()。除了 Internet Explorer。我知道 😞 所以如果你需要支持旧版浏览器,请使用旧方法 😕

浏览器支持:Math.trunc

社区意见

按位运算符解决方案

双按位非~~

console.log(~~80.6); // 80
Enter fullscreen mode Exit fullscreen mode

感谢:@Jorgert120

按位或|

console.log(80.6 | 0); // 80
Enter fullscreen mode Exit fullscreen mode

感谢:@mac_experts

资源

MDN Web 文档:Math.trunc
MDN Web 文档:parseInt
MDN Web 文档:位运算符
JS 提示:对字符串使用 parseInt,而不是对数字使用
2ality:parseInt 并不总是正确地转换为整数


感谢阅读❤
打个招呼!Instagram | Twitter | Facebook | Medium |博客

文章来源:https://dev.to/samanthaming/number-truncation-in-javascript-1li
PREV
将数组作为函数参数传递
NEXT
如何避免 Vue 中出现 null 的空类