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

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