點燈坊

失くすものさえない今が強くなるチャンスよ

4 Ways to Convert from String to Number

Sam Xiao's Avatar 2021-12-19

We can convert from String to Number by Number, parseInt, + or ~~ operator.

Version

ECMAScript 2015

Number

let x = '123'
Number (x) // ? 
  • Number is a constructor function to create a Wrapper Object by new
  • Number is a normal function to convert from String to Number

number000

parseInt

let x = '123'
parseInt (x) // ?

We can also use parseInt to convert from String to Number.

number003

+ Operator

let x = '123';
+x // ?

We can also use + operator to convert from String to Number.

number001

~~ Operator

let x = '123'
~~x // ?
  • ~ is a bitwise NOT operator, it convert to Number first, just like -n - 1
  • ~~ is -(-n - 1) - 1, it equals to (n + 1) - 1, and back to n

number002

Conclusion

  • Number and parseInt is the most intuitive way to convert from String to Number
  • + operator is the shortest way to convert from String to Number

Reference

Dr.Axel Rauschmayer, Speaking JavaScript
Bret Cameron, 12 JavaScript Tricks You Won’t Find in Most Tutorials