Earlier we’ve seen 6 ways to convert a number to a string in JavaScript. Now, let’s have a look at how you can convert a string to a number in JavaScript:
1. Convert using the Number constructor
const myString = '10'
const myNumber = Number(myString)
console.log(myNumber)
console.log(typeof myNumber)
//output
10
number
Code language: JavaScript (javascript)
2. Convert using parseInt()
const anotherString = '20'
const anotherNumber = parseInt(anotherString)
console.log(anotherNumber)
console.log(typeof anotherNumber)
//output
20
number
Code language: JavaScript (javascript)
3. Convert using parseFloat()
const yetAnotherString = '30'
const yetAnotherNumber = parseFloat(yetAnotherString)
console.log(yetAnotherNumber)
console.log(typeof yetAnotherNumber)
//output
30
number
Code language: JavaScript (javascript)
4. Convert by multiplying by 1
const seriouslyAnotherString = '40'
const seriouslyAnotherNumber = seriouslyAnotherString * 1
console.log(seriouslyAnotherNumber)
console.log(typeof seriouslyAnotherNumber)
//output
40
number
Code language: JavaScript (javascript)
5. Convert by dividing by 1
const areYouKiddingAnotherString = '50'
const areYouKiddingAnotherNumber = areYouKiddingAnotherString / 1
console.log(areYouKiddingAnotherNumber)
console.log(typeof areYouKiddingAnotherNumber)
//output
50
number
Code language: JavaScript (javascript)