Converting & Rounding
Because math requires rounding or remainder work, we have methods to round numbers, convert them, etc.
Strongly typed languages require the programmer to select a variable type for numbers. For example, an
integeris a whole number only such as -7 and 30. A
Let's say you are requesting input from the user. They are to type in a number representing the grade they are in and you will be adding 5 to guess their age. You prompt the user, add 5, and output the results... It would go a little like this:
let grade = prompt("Please enter your current grade");
let output = grade + 5;
The only problem is that the grade being entered by the user is coming back as a
+operator on strings means to concatenate them. Check it out:
To avoid this, we need to make sure our
gradevariable is being treated as a number. As always, there is more than one way to do this.
grade = Number(grade); // Returns a numeric value of grade, if possible
parseInt(string), or a decimal value,
grade = parseInt(grade); // Returns an integer representation of grade
It should be noted that the preferred method is to use the
Numberobject as it has better handling of non-numeric input.
toString()method which returns a string representation of that variable / object.
let num = 15;
let fifteen = num.toString();
console.log(typeof num); // number
console.log(typeof fifteen); // string