在 JavaScript 中截断/舍入整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10149806/
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
Truncate/round whole number in JavaScript?
提问by Eric
For a script I'm writing, I need display a number that has been rounded, but not the decimal or anything past it. I've gotten down to rounding it to the third place, but I'm not sure how to go about just dropping the decimal and everything past it, as it doesn't seem like JavaScript has a substr
function like PHP does.
对于我正在编写的脚本,我需要显示一个四舍五入的数字,但不能显示小数点或任何超过它的数字。我已经把它四舍五入到第三位,但我不知道如何只去掉小数点和它后面的所有内容,因为 JavaScript 似乎没有substr
像 PHP 那样的功能。
Any recommendations?
有什么建议吗?
回答by Ry-
If you have a string, parse it as an integer:
如果您有string,请将其解析为整数:
var num = '20.536';
var result = parseInt(num, 10); // 20
If you have a number, ECMAScript 6 offers Math.trunc
for completely consistent truncation, already available in Firefox 24+ and Edge:
如果你有一个 number,ECMAScript 6 提供Math.trunc
完全一致的截断,已经在 Firefox 24+ 和 Edge 中可用:
var num = -2147483649.536;
var result = Math.trunc(num); // -2147483649
If you can't rely on that and will always have a positive number, you can of course just use Math.floor
:
如果你不能依赖它并且总是有一个正数,你当然可以使用Math.floor
:
var num = 20.536;
var result = Math.floor(num); // 20
And finally, if you have a number in [−2147483648, 2147483647], you can truncate to 32 bits using any bitwise operator. | 0
is common, and >>> 0
can be used to obtain an unsigned 32-bit integer:
最后,如果您在 [−2147483648, 2147483647] 中有一个数字,则可以使用任何按位运算符将其截断为 32 位。| 0
很常见,>>> 0
可用于获取无符号 32 位整数:
var num = -20.536;
var result = num | 0; // -20
回答by BlinkyTop
Travis Pessetto's answer along with mozey's trunc2
function were the only correct answers, considering how JavaScript represents very small or very large floating point numbers in scientific notation.
trunc2
考虑到 JavaScript 如何用科学记数法表示非常小的或非常大的浮点数,Travis Pessetto 的答案以及 mozey 的函数是唯一正确的答案。
For example, parseInt(-2.2043642353916286e-15)
will not correctly parse that input. Instead of returning 0
it will return -2
.
例如,parseInt(-2.2043642353916286e-15)
不会正确解析该输入。0
它将返回而不是返回-2
。
This is the correct (and imho the least insane) way to do it:
这是正确的(恕我直言是最不疯狂的)方法:
function truncate(number)
{
return number > 0
? Math.floor(number)
: Math.ceil(number);
}
回答by Travis Pessetto
I'll add my solution here. We can use floor when values are above 0 and ceil when they are less than zero:
我会在这里添加我的解决方案。我们可以在值大于 0 时使用 floor,当值小于零时使用 ceil:
function truncateToInt(x)
{
if(x > 0)
{
return Math.floor(x);
}
else
{
return Math.ceil(x);
}
}
Then:
然后:
y = truncateToInt(2.9999); // results in 2
y = truncateToInt(-3.118); //results in -3
回答by mozey
Convert the number to a string and throw away everything after the decimal.
将数字转换为字符串并丢弃小数点后的所有内容。
trunc = function(n) { return Number(String(n).replace(/\..*/, "")) }
trunc(-1.5) === -1
trunc(1.5) === 1
Edit 2013-07-10
编辑 2013-07-10
As pointed out by minitech and on second thought the string method does seem a bit excessive. So comparing the various methods listed here and elsewhere:
正如 minitech 所指出的,再次考虑字符串方法似乎有点过分。因此,比较此处和其他地方列出的各种方法:
function trunc1(n){ return parseInt(n, 10); }
function trunc2(n){ return n - n % 1; }
function trunc3(n) { return Math[n > 0 ? "floor" : "ceil"](n); }
function trunc4(n) { return Number(String(n).replace(/\..*/, "")); }
function getRandomNumber() { return Math.random() * 10; }
function test(func, desc) {
var t1, t2;
var ave = 0;
for (var k = 0; k < 10; k++) {
t1 = new Date().getTime();
for (var i = 0; i < 1000000; i++) {
window[func](getRandomNumber());
}
t2 = new Date().getTime();
ave += t2 - t1;
}
console.info(desc + " => " + (ave / 10));
}
test("trunc1", "parseInt");
test("trunc2", "mod");
test("trunc3", "Math");
test("trunc4", "String");
The results, which may vary based on the hardware, are as follows:
结果可能因硬件而异,如下所示:
parseInt => 258.7
mod => 246.2
Math => 243.8
String => 1373.1
The Math.floor / ceil method being marginally faster than parseInt and mod. String does perform poorly compared to the other methods.
Math.floor / ceil 方法比 parseInt 和 mod 稍微快一点。与其他方法相比,字符串确实表现不佳。
回答by gilly3
回答by Asad Manzoor
Math.trunc()function removes all the fractional digits.
Math.trunc()函数删除所有小数位。
For positive number it behaves exactly the same as Math.floor():
对于正数,它的行为与 Math.floor() 完全相同:
console.log(Math.trunc(89.13349)); // output is 89
For negative numbers it behaves same as Math.ceil():
对于负数,它的行为与 Math.ceil() 相同:
console.log(Math.trunc(-89.13349)); //output is -89