在JavaScript中截断/舍入整数? [英] Truncate/round whole number in JavaScript?

查看:68
本文介绍了在JavaScript中截断/舍入整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在编写的脚本,我需要显示一个已舍入的数字,但不是十进制或其后的任何内容。我已经把它四舍五入到第三位了,但是我不知道如何去掉小数和一切都超过它,因为它似乎没有JavaScript有一个 substr 像PHP这样的函数。

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.

有什么建议吗?

推荐答案

如果您有字符串,请将其解析为整数:

If you have a string, parse it as an integer:

var num = '20.536';
var result = parseInt(num, 10);  // 20

如果您有数字,ECMAScript 6会提供 Math.trunc 用于完全一致的截断,已在Firefox 24+和Edge中提供:

If you have a number, ECMAScript 6 offers Math.trunc for completely consistent truncation, already available in Firefox 24+ and Edge:

var num = -2147483649.536;
var result = Math.trunc(num);  // -2147483649

如果您不能依赖它并且总是有一个正数,那么你当然可以使用 Math.floor

If you can’t rely on that and will always have a positive number, you can of course just use Math.floor:

var num = 20.536;
var result = Math.floor(num);  // 20

最后,如果你在[− 2147483648,2147483647]中有一个数字,那么你可以使用任何按位运算符截断为32位。 | 0 很常见,>>> 0 可用于获取无符号的32位整数:

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:

var num = -20.536;
var result = num | 0;  // -20

这篇关于在JavaScript中截断/舍入整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆