How to convert a string (with leading zero or not) to an integer?
How to convert a string (with leading zero or not) to an integer? For example,开发者_C百科 '08'
to 8
.
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
- Number() - MDC
- Converting to number (JavaScript Type-Conversion) - jibbering.com
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
you can use parseInt()
; with base 10 or parseFloat();
to parse float
Use the parseInt
function. Reference: link
精彩评论