Converting a string to an integer in JavaScript is something that we may have to do sometimes.
In this article, we’ll look at how to convert a string to an integer with JavaScript.
The Number Function
We can use tyhe Number
function to convert an integer string into an integer.
For instance, we can write:
const num = Number("1000")
console.log(num)
Then num
is 1000.
The parseInt Function
The parseInt
function also lets us convert an integer string into an integer.
It takes the number string and the base of the number we’re converting respectively.
For instance, we can write:
const num = parseInt("1000", 10);
console.log(num)
Then we get the same result as the previous example.
Unary Plus Operator
The unary plus operator also converts a string to an integer.
So we can put the + operator right before the integer to convert it to a number.
For instance, we can write:
const num = +"1000"
console.log(num)
and get the same result.
Math.floor
The Math.floor
method rounds a number down to the nearest integer.
It also accepts a number string, so we can pass it into the Math.floor
method, and it’ll return the integer rounded down to the nearest integer.
For instance, we can write:
const num = Math.floor("1000.05")
console.log(num)
And we get that num
is 1000.
Math.round
The Math.round
method also lets us round a number.
The rule for rounding is that if the fractional portion of the argument is bigger than 0.5, then the argument is rounded to the next highest integer in absolute value.
Otherwise, it’ll be rounded to the nearest integer with the lower absolute value.
It also takes a string and will do the conversion to a number before rounding.
For instance, we can write:
const num = Math.round("1000.05")
console.log(num)
The parseFloat Function
The parseFloat
function lets us convert a floating point number string into a number.
It also works with converting integer strings into integers.
For instance, we can write:
const num = parseFloat("1000")
console.log(num)
Conclusion
There are many ways to convert an integer string to an integer with JavaScript.