从变量中去掉小数点
我有一系列带有小数点和几个零的变量。如何删除变量,使其从 1.000 变为 1?
I have a series of variables that have a decimal point and a few zeros. How do I strip the variable so it goes from 1.000 to 1?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
parseInt 是最慢的方法
math.floor 是第二慢的方法,
此处未列出的更快的方法是:
var myInt = 1.85 | 0;
myInt = 1;
var myInt = 1.85>> 0;
myInt = 1;
速度测试在这里完成:
http://jsperf.com/math-floor-vs-math-round-vs-解析/2
parseInt is the slowest method
math.floor is the 2nd slowest method
faster methods not listed here are:
var myInt = 1.85 | 0;
myInt = 1;
var myInt = 1.85 >> 0;
myInt = 1;
Speed tests done here:
http://jsperf.com/math-floor-vs-math-round-vs-parseint/2
要将数字四舍五入到最接近的整数,您可以使用 Math.round() ,如下所示:
For rounding numbers to the nearest Integer you can use
Math.round()
like so:为此,您不需要 jQuery。
您可以使用 parseInt 就可以了。从页面:
You don't need jQuery for this.
You can use parseInt just fine. From the page:
这是另一个很好的例子:
我经常使用
Math.round
和toLocateString
将包含小数位的数字转换为更易读的字符串,并带有千位分隔符:我发现这在从 JSON Web 服务加载小数值时很有用,并且需要在网页上以更友好的格式显示它们(当然,当我不需要显示所有小数位时)。
Here's another nice example:
I often use
Math.round
andtoLocateString
to convert numbers containing decimal places, into a more readable string, with thousand separators:I find this useful when loading decimal values from, say a JSON Web Service, and need to display them in a friendlier format on a web page (when, of course, I don't need to display all of the decimal places).
更快、更有效的方法是使用 JavaScript 的 bitwise运算符,如下所示:
|
(OR 运算符)会将数字视为 32 位(二进制0s
和1s
),然后根据操作数返回所需的结果,在本例中将生成一个去除所有小数位的整数。A faster, more efficient way would be to use JavaScript's bitwise operators, like so:
The
|
(OR operator) will treat the numbers as 32-bit (binary0s
and1s
), followed by returning the desired result depending on the operands, which in this case would result to an integer stripped of all decimal places.我建议您使用名为
Math.trunc()
的东西...将您的数字放在括号中。我不建议您使用 Math.round() 的原因是它可能会更改十进制数的整数部分,尽管您可以使用 Math.round,但有些人不希望这样做() 如果您知道要获取最接近的整数。I suggest you use something called
Math.trunc()
... put your number in the parentheses. The reason I don't suggest you useMath.round()
is that it might change the integer part of your decimal number which some people won't want though you can useMath.round()
if you know you want to get the closest integer.简单地...
...假设您想将
1.7
舍入为2
。如果不是,请使用Math.floor
将1.7
转换为1
。Simply...
...assuming you want to round
1.7
to2
. If not, useMath.floor
for1.7
to1
.使用parseInt();
use
parseInt();
使用
number = ~~number
这是最快的替代
Math.floor()
Use
number = ~~number
This is the fastest substitute to
Math.floor()
使用Math.trunc()。它完全按照你的要求做。它去掉了小数点。
https://developer.mozilla.org/en -US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
Use
Math.trunc()
. It does exactly what you ask. It strips the decimal.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc