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
integer
is a whole number only such as -7 and 30. A double
or float
contains values after the decimal like 6.5 or -3.14.
Javascript, on the other hand, treats any variable as a value or string interchangeably, including decimal values. It is a weakly or dynamically typed language.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;
console.log(output);
The only problem is that the grade being entered by the user is coming back as a
String
and the +
operator on strings means to concatenate them. Check it out:To avoid this, we need to make sure our
grade
variable is being treated as a number. As always, there is more than one way to do this.The Number object in Javascript has many useful functions, not the least of which is returning a new Number if we pass it a string.
grade = Number(grade); // Returns a numeric value of grade, if possible
Javascript also has two methods to parse (or convert) a string into a whole number value,
parseInt(string)
, or a decimal value, parseFloat(string)
.
grade = parseInt(grade); // Returns an integer representation of grade
It should be noted that the preferred method is to use the
Number
object as it has better handling of non-numeric input.Going the other direction is decidedly simpler. Almost anything in Javascript has a
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
Last modified 4yr ago