Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parseInt a string with leading 0

How to parseInt "09" into 9 ?

like image 851
khelll Avatar asked Oct 09 '09 17:10

khelll


People also ask

Does parseInt remove leading zeros?

Use parseInt() to remove leading zeros from a number in JavaScript.

How do you add leading zeros to a string?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.

How do you cut leading zeros on a string?

The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String. The ^0+(?! $)"; To remove the leading zeros from a string pass this as first parameter and “” as second parameter.


2 Answers

include the radix:

parseInt("09", 10); 
like image 116
Gabe Moothart Avatar answered Oct 08 '22 12:10

Gabe Moothart


This has been driving me nuts -parseInt("02") works but not parseInt("09").

As others have said, the solution is to specify base 10:

parseInt("09", 10); 

There's a good explanation for this behaviour here

... In Javascript numbers starting with zero are considered octal and there's no 08 or 09 in octal, hence the problem.

like image 33
codeulike Avatar answered Oct 08 '22 13:10

codeulike