JavaScript : Different ways to convert String into Integer (Number)

Shivaji Ranaware
Aug 29, 2017 · 1 min read

There are many ways to convert a String to a Number.

  1. Number function : The simplest way would be to use the native Number function.
    var x = Number(‘100’); // return 100 with Number type
  2. parseInt : default way (without radix)
    var x = parseInt(‘100’); // return 100 with Number type
  3. parseInt : with Radix (decimal)
    var x = parseInt(‘100’,10); // return 100 with Number type
  4. parseFloat :
    var x = parseFloat(‘100’); // return 100 with Number type
  5. Bitwise not ~ : You can use that to convert a string to an integer only, but it’s not for floating numbers. The good thing about it is that it will return “0” if a character appears.
    var x = ~~‘100’; // return 100 with Number type
    var x = ~~‘100.12’; // return 100 with Number type
    var x = ~~100.12; // return 100 with Number type
    var x = ~~‘xyz’; // return 0 with Number type

Use of Unary operators

6. Divide by 1 : var x = ‘100’ / 1; // return 100 with Number type

7. Multiply by 1 : var x = ‘100’ * 1; // return 100 with Number type

8. Minus by 0 : var x = ‘100’ — 0 ; // return 100 with Number type

9. Operator ‘+’ : var x = +‘100’; // return 100 with Number type

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade