12

How to convert a string (with leading zero or not) to an integer? For example, '08' to 8.

Domspan
  • 153
  • 1
  • 7

4 Answers4

18

There are several ways to convert a string to a number, I prefer to use the unary + operator:

var number = +"08"; // 8

This is the equivalent of writing:

var number = Number("08"); // 8

Unlike parseInt(), when using + or Number() no radix is necessary because the internal number conversion will not parse octal numbers. If you want the parseInt() or parseFloat() methods, it's also pretty simple:

var number = parseInt("08", 10); // 8

parseInt and parseFloat are less reliable for user input because an invalid numeric literal might be considered salvageable by these functions and return an unexpected result. Consider the following:

parseInt("1,000");   // -> 1, not 1000
+"1,000";            // -> NaN, easier to detect when there's a problem

Extra Reading

Community
  • 1
  • 1
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • what about 010 number not an string ? parseInt(), Number, +, didn't work – Umair Ahmed Jan 10 '17 at 13:04
  • @Umair: `010` is already a number. In "loose mode" or older browsers, the number will be 8. In strict mode, a syntax error will be thrown (but you can use `0o10` if you *transpile* with Babel or use newer browsers exclusively) – Andy E Jan 12 '17 at 08:56
  • yes your are right it's already number i wanna get decimal value of this number or remove leading 0 how can i do – Umair Ahmed Jan 12 '17 at 10:40
  • 1
    @Umair: that seems really odd. You can basically convert the number back into an octal string, then parse it correctly. `+(010.toString(8))`, for instance. – Andy E Jan 12 '17 at 12:09
6

Use parseInt() with the radix argument. This disables autodetection of the base (leading 0 -> octal, leading 0x -> hex):

var number = parseInt('08', 10);
// number is now 8
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
3

you can use parseInt(); with base 10 or parseFloat(); to parse float

KJYe.Name
  • 16,969
  • 5
  • 48
  • 63
2

Use the parseInt function. Reference: link

Cassie Dee
  • 3,145
  • 2
  • 18
  • 11