2011-11-17 113 views
17

有一个快速的JS问题。 math.round和parseInt有什么区别?math.round vs 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> 

,它使用parseInt函数。如果我想使用math.round,还有什么我需要做的,它知道要相应地限制小数位数?

换句话说,math.round是否必须以某种方式进行格式化?

+5

你比较苹果和桔子。 'parseInt'将一个字符串转换为一个整数,而'Math.round()' - 很好地处理了一个浮点数。 –

+0

但parseInt的东西是,它似乎总是将数字,如fractor例如,以合理数量的字符,而math.round似乎只圆整数 – Chris

+0

旁注:说到舍入,parseInt是比Math.round慢得多:http://jsperf.com/math-floor-vs-math-round-vs-parseint/55 –

回答

33

这两个函数真的很不一样。

parseInt()从字符串中提取一个数字,例如,

parseInt('1.5') 
// => 1 

Math.round()回合数最接近的整数:

Math.round('1.5') 
// => 2 

parseInt()可以通过去除多余的文字获得其编号,例如:

parseInt('12foo') 
// => 12 

然而,Math.round不会:

Math.round('12foo') 
// => NaN 

你或许应该使用parseFloatMath.round因为你从用户获取输入:

var number = parseFloat(prompt('Enter number:')); 
var rounded = Math.round(number); 
+0

有没有办法让Math.round变成小数点后3位? – Chris

+6

我知道这样做的唯一方法是作弊:'Math.round(1.23456 * 1000)/ 1000' –

+0

这工作:)非常感谢sooo! – Chris

3

Math.round将数字四舍五入为最接近的整数。 parseInt会向你保证,该值为数

那么,你需要的是这样的:

number = parseInt(number); 

if (isNan(number) || number == 0){ 
    document.write("Invalid Input <br>"); 
    count++; 
}

这将确保您的使用已经投入了许多