如何在JavaScript中舍入数字? [英] How do I round a number in JavaScript?
问题描述
在处理一个项目时,我遇到了一个由前雇员创建的JS脚本,它基本上以
Name:Value
Name2:Value2
等。
这个标记是值有时可以是浮点数(具有不同的精度),整数,甚至是 2.20011E + 17
。我想要输出的是纯粹的整数。不过,我不太了解JavaScript。我将如何去写一个方法,这些有时浮动,使他们整数?
你要转换你的输入到一个数字,然后四舍五入他们:
$ $ p $ $ code函数toInteger(数字){
返回Math.round(// round到最接近的整数
数字(数字)//类型转换您的输入
);
};
或者作为单行:
function toInt(n){return Math.round(Number(n)); };
使用不同的值进行测试:
toInteger(2.5); // 3
toInteger(1000); // 1000
toInteger(12345.12345); // 12345
toInteger(2.20011E + 17); // 220011000000000000
While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of
Name : Value
Name2 : Value2
etc.
The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17
. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?
You hav to convert your input into a number and then round them:
function toInteger(number){
return Math.round( // round to nearest integer
Number(number) // type cast your input
);
};
Or as a one liner:
function toInt(n){ return Math.round(Number(n)); };
Testing with different values:
toInteger(2.5); // 3
toInteger(1000); // 1000
toInteger("12345.12345"); // 12345
toInteger("2.20011E+17"); // 220011000000000000
这篇关于如何在JavaScript中舍入数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!