Javascript math.round 与 parseInt
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8170865/
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
math.round vs parseInt
提问by Chris
Have a quick JS question. What is the difference between math.round and parseInt?
有一个快速的 JS 问题。math.round 和 parseInt 有什么区别?
I made a JS script to sum the inverses of prompted numbers:
我做了一个 JS 脚本来求和提示数字的倒数:
<script type="text/javascript">
var numRep = prompt("How many repetitions would you like to run?");
var sum = 0;
var count = 0;
var i = 1; //variable i becomes 1
while (i <= numRep) {// repeat 5 times
var number = prompt("Please enter a non zero integer");
if(number==0){
document.write("Invalid Input <br>");
count++;
}
else{
document.write("The inverse is: " + 1/number + "<br>");
sum = sum + (1/parseInt(number)); //add number to the sum
}
i++; //increase i by 1
}
if (sum==0){
document.write("You did not enter valid input");}
else { document.write("The sum of the inverses is: " + sum); //display sum
}
</script></body></html>
and it uses parseInt. If I wanted to makeit use math.round, is there anything else I need to do so that It knows to limit the number of decimal places accordingly?
它使用 parseInt。如果我想让它使用 math.round,还有什么我需要做的,以便它知道相应地限制小数位数?
In other words, does math.round have to be formatted in a certain way?
换句话说, math.round 是否必须以某种方式格式化?
回答by Tim Morgan
The two functions are really quite different.
这两个功能真的很不一样。
parseInt()
extracts a number from a string, e.g.
parseInt()
从字符串中提取一个数字,例如
parseInt('1.5')
// => 1
Math.round()
rounds the number to the nearest whole number:
Math.round()
将数字四舍五入到最接近的整数:
Math.round('1.5')
// => 2
parseInt()
can get its number by removing extra text, e.g.:
parseInt()
可以通过删除多余的文本来获取其编号,例如:
parseInt('12foo')
// => 12
However, Math.round will not:
但是, Math.round 不会:
Math.round('12foo')
// => NaN
You should probably use parseFloat
and Math.round
since you're getting input from the user:
您可能应该使用parseFloat
并且Math.round
因为您从用户那里获得输入:
var number = parseFloat(prompt('Enter number:'));
var rounded = Math.round(number);
回答by locrizak
Math.round
will round the number to the nearest integer. parseInt
will assure you that the value is a number
Math.round
将数字四舍五入到最接近的整数。parseInt
将向您保证该值是一个数字
So what you will need is something like this:
所以你需要的是这样的:
number = parseInt(number);
if ( isNan(number) || number == 0 ){
document.write("Invalid Input <br>");
count++;
}
This will assure you that the use has put in a number
这将向您保证使用已经输入了一个数字
回答by Jakub Konecki
Math.round
expects a number, parseInt
expects a string.
Math.round
需要一个数字,parseInt
需要一个字符串。
Use parseInt('12345', 10)
for parsing 10-based numbers.
使用parseInt('12345', 10)
解析为基础的10个号码。