Skip to content Skip to sidebar Skip to footer

Why Javascript Parseint Ignoring Leading Zeros In The String?

I am trying to convert a string to number, which is '09' parseInt('09') //returns 9 always What is the best way to get the number with leading zero and it would be better if someo

Solution 1:

An int cannot have leading zeroes, since they don't have any mathematical meaning.

To store a number, languages use a binary representation (don't forget everything is 0s and 1s in the end). This representation is the same for 9, 09, or 00009. When the number must be printed, it is converted back to a string representation, so you lose the leading zeroes.

If you need to store/remember the 0s, your only choice is to store the string representation of the number.

What you could do is storing both the number and string representation, like this:

functionMyInt(s){
    this.asString = s;
    this.num = parseInt(s);
}


var i = newMyInt("09");
console.log(i.num); // 9console.log(i.asString); // 09

Take note that leading 0 don't have any value for int. If want to use for display purpose use string and for calculation part use parseInt(someval)

Solution 2:

parseInt takes two parameters: string and radix.

radix tells parseInt how to convert a string to a number.

If you leave the radix out, the rules are somewhat simple for how it decides what radix to use:

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

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
  • If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.

  • If the input string begins with any other value, the radix is 10 (decimal).

That said, you are using a function whose non-abbreviated name is "Parse Integer." You cannot make it retain leading zeros, because leading zeros have no mathematical value.

Post a Comment for "Why Javascript Parseint Ignoring Leading Zeros In The String?"