javascript trunc() 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2125715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript trunc() function
提问by Dan
I want to truncate a number in javascript, that means to cut away the decimal part:
我想在javascript中截断一个数字,这意味着去掉小数部分:
trunc ( 2.6 ) == 2
截断 (2.6) == 2
trunc (-2.6 ) == -2
截断 (-2.6) == -2
After heavy benchmarking my answer is:
经过大量基准测试后,我的答案是:
function trunc (n) {
return ~~n;
}
// or?
function trunc1 (n) {
?? ?return n | 0;
?}
回答by CMS
As an addition to the @Daniel's answer, if you want to truncate always towards zero, you can:
作为@Daniel答案的补充,如果您想始终向零截断,您可以:
function truncate(n) {
return n | 0; // bitwise operators convert operands to 32-bit integers
}
Or:
或者:
function truncate(n) {
return Math[n > 0 ? "floor" : "ceil"](n);
}
Both will give you the right results for both, positive and negative numbers:
两者都会为您提供正数和负数的正确结果:
truncate(-3.25) == -3;
truncate(3.25) == 3;
回答by Daniel Vassallo
For positive numbers:
对于正数:
Math.floor(2.6) == 2;
For negative numbers:
对于负数:
Math.ceil(-2.6) == -2;
回答by Ivan
You can use toFixedmethod that also allows to specify the number of decimal numbers you want to show:
您可以使用toFixed方法,该方法还允许指定要显示的十进制数的数量:
var num1 = new Number(3.141592);
var num2 = num1.toFixed(); // 3
var num3 = num1.toFixed(2); // 3.14
var num4 = num1.toFixed(10); // 3.1415920000
Just note that toFixedrounds the number:
请注意toFixed对数字进行四舍五入:
var num1 = new Number(3.641592);
var num2 = num1.toFixed(); // 4
回答by Jochen
I use
我用
function trunc(n){
return n - n % 1;
}
because it works over the whole float range and should (not measured) be faster than
因为它适用于整个浮点范围并且应该(未测量)比
function trunc(n) {
return Math[n > 0 ? "floor" : "ceil"](n);
}
回答by Syntheticheroism
In case it wasn't available before and for anyone else who stumbles upon this thread, you can now simply use the trunc() function from the Math library, like so:
如果它之前不可用,并且对于偶然发现此线程的任何其他人,您现在可以简单地使用 Math 库中的 trunc() 函数,如下所示:
let x = -201;
x /= 10;
console.log(x);
console.log(Math.trunc(x));
>>> -20.1
>>> -20

