Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript parseInt() with leading zeros

Tags:

javascript

People also ask

Does parseInt remove leading zeros?

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

Does parseInt work with negative numbers JavaScript?

parseInt understands exactly two signs: + for positive, and - for negative. It is done as an initial step in the parsing after whitespace is removed.

What happens if you use parseInt () to convert a string containing decimal value?

What if you use parseInt() to convert a string containing decimal value? Explanation: JavaScript's parseInt function is all about converting a string to an integer. The function takes a string value as an argument and converts it to a numerical value with no decimal places, or alternatively the value NaN. 39.


This is because if a number starts with a '0', it's treated as base 8 (octal).

You can force the base by passing the base as the 2nd parameter.

parseInt("09", 10) // 9

According to the docs, the 2nd parameter is optional, but it's not always assumed to be 10, as you can see from your example.


Calls to parseInt should always specify a base in the second argument:

parseInt("08", 10);

Earlier versions of JavaScript treat strings starting with 0 as octal (when no base is specified) and neither 08 nor 09 are valid octal numbers.

From the Mozilla documentation:

If radix is undefined or 0, JavaScript assumes the following:

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).
  • If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
  • If the input string begins with any other value, the radix is 10 (decimal).

If the first character cannot be converted to a number, parseInt returns NaN.

And from the ECMAScript 3 standard:

When radix is 0 or undefined and the string's number begins with a 0 digit not followed by an x or X, then the implementation may, at its discretion, interpret the number either as being octal or as being decimal. Implementations are encouraged to interpret numbers in this case as being decimal.

The latest version of JavaScript (ECMAScript 5) abandons this behavior, but you should still specify the radix to satisfy older browsers.


There is a Radix parameter

parseInt(value, base)

Where base is the radix.

In this case you are evaluating base10 (decimal) numbers, therefore use

parseInt(value, 10);

This doesn't seem to be completely valid in new browsers. Internet Explorer 9 and 10 will return 8 if you execute 'parseInt("08")' whereas Internet Explorer 8 and previous versions will return 0 (IE10 in quirks mode will also return 0).

The latest version of Chrome also returns 8 so they must have changed the interpretation recently.