有一个快速的JS问题.math.round和parseInt有什么区别?
我制作了一个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>
Run Code Online (Sandbox Code Playgroud)
它使用parseInt.如果我想makeit使用math.round,还有什么我需要做的,它知道相应地限制小数位数吗?
换句话说,math.round必须以某种方式格式化吗?
Tim*_*gan 39
这两个功能真的很不一样.
parseInt()
从字符串中提取数字,例如
parseInt('1.5')
// => 1
Run Code Online (Sandbox Code Playgroud)
Math.round()
将数字四舍五入到最接近的整数:
Math.round('1.5')
// => 2
Run Code Online (Sandbox Code Playgroud)
parseInt()
可以通过删除额外的文本来获取其编号,例如:
parseInt('12foo')
// => 12
Run Code Online (Sandbox Code Playgroud)
但是,Math.round不会:
Math.round('12foo')
// => NaN
Run Code Online (Sandbox Code Playgroud)
您应该使用parseFloat
并且Math.round
因为您从用户那里获得了输入:
var number = parseFloat(prompt('Enter number:'));
var rounded = Math.round(number);
Run Code Online (Sandbox Code Playgroud)