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?
parseInt() easily converts your string to a rounded integer. In these cases, simply define your string argument and set the radix to 10 (or if you have a special use-case, another numerical value).
parseFloat( ) parseFloat() is quite similar to parseInt() , with two main differences. First, unlike parseInt() , parseFloat() does not take a radix as an argument. This means that string must represent a floating-point number in decimal form (radix 10), not octal (radix 8) or hexadecimal (radix 6).
Math. round() - rounds to the nearest integer (if the fraction is 0.5 or greater - rounds up) Math. floor() - rounds down.
Hence for converting some non-numeric value to number we should always use Number() function. eg. There are various corner case to parseInt() functions as it does redix conversion, hence we should avoid using parseInt() function for coersion purposes.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With