Chris
Chris

Reputation: 1939

math.round vs parseInt

Have a quick JS question. What is the difference between math.round and parseInt?

I made a JS script to sum the inverses of prompted numbers:

    <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?

In other words, does math.round have to be formatted in a certain way?

Upvotes: 31

Views: 38963

Answers (3)

Tim Morgan
Tim Morgan

Reputation: 1184

The two functions are really quite different.

parseInt() extracts a number from a string, e.g.

parseInt('1.5')
// => 1

Math.round() rounds the number to the nearest whole number:

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

parseInt() can get its number by removing extra text, e.g.:

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

However, Math.round will not:

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

You should probably use parseFloat and Math.round since you're getting input from the user:

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

Upvotes: 55

Jakub Konecki
Jakub Konecki

Reputation: 46008

Math.round expects a number, parseInt expects a string.

Use parseInt('12345', 10) for parsing 10-based numbers.

http://www.javascripter.net/faq/convert2.htm

Upvotes: 3

locrizak
locrizak

Reputation: 12281

Math.round will round the number to the nearest integer. parseInt will assure you that the value is a number

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

Upvotes: 3

Related Questions