189

Possible Duplicate:
Truncate leading zeros of a string in Javascript

What is the simplest and cross-browser compatible way to remove leading zeros from a number in Javascript ?

e.g. If I have a textbox value as 014 or 065, it should only return 14 or 65

Community
  • 1
  • 1
copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • 3
    What for? Do you want to format the text in the field or do you just want to get the correct decimal value? `parseInt` takes a second parameter, the radix, which should always be set! Set it to `10`. – Felix Kling Jul 13 '11 at 09:01
  • @felix. you already typed this as a comment :) +1 for that unary `+` didn't think of it. – naveen Jul 13 '11 at 09:12

3 Answers3

304

We can use four methods for this conversion

  1. parseInt with radix 10
  2. Number Constructor
  3. Unary Plus Operator
  4. Using mathematical functions (subtraction)

const numString = "065";

//parseInt with radix=10
let number = parseInt(numString, 10);
console.log(number);

// Number constructor
number = Number(numString);
console.log(number);

// unary plus operator
number = +numString;
console.log(number);

// conversion using mathematical function (subtraction)
number = numString - 0;
console.log(number);


Update(based on comments): Why doesn't this work on "large numbers"?

For the primitive type Number, the safest max value is 253-1(Number.MAX_SAFE_INTEGER).

console.log(Number.MAX_SAFE_INTEGER);

Now, lets consider the number string '099999999999999999999' and try to convert it using the above methods

const numString = '099999999999999999999';

let parsedNumber = parseInt(numString, 10);
console.log(`parseInt(radix=10) result: ${parsedNumber}`);

parsedNumber = Number(numString);
console.log(`Number conversion result: ${parsedNumber}`);

parsedNumber = +numString;
console.log(`Appending Unary plus operator result: ${parsedNumber}`);

parsedNumber = numString - 0;
console.log(`Subtracting zero conversion result: ${parsedNumber}`);

All results will be incorrect.

That's because, when converted, the numString value is greater than Number.MAX_SAFE_INTEGER. i.e.,

99999999999999999999 > 9007199254740991

This means all operation performed with the assumption that the stringcan be converted to number type fails.

For numbers greater than 253, primitive BigInt has been added recently. Check browser compatibility of BigInthere.

The conversion code will be like this.

const numString = '099999999999999999999';
const number = BigInt(numString);

P.S: Why radix is important for parseInt?

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)
  • If the input string begins with any other value, the radix is 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

naveen
  • 53,448
  • 46
  • 161
  • 251
  • 4
    It isn't clear from the question if it's ever the case, but this also removes anything after the decimal point. – pimvdb Jul 13 '11 at 09:10
  • 3
    parseInt("08") == 0, it's a bug, use another answer. – Greg Dec 09 '11 at 21:50
  • 2
    @Greg. Thanks for the info. But I did not get the relevance. `parseInt("08", 10)` is indeed `8` – naveen Dec 11 '11 at 11:01
  • 9
    might want to mention that the radix is important, so that people don't make the same mistake as greg. – Zach Lysobey Feb 06 '13 at 18:58
  • Heads up to anyone using this solution: Make sure you use the second parameter. parseInt("08") == 0, whereas parseInt("08",10) == 10 – David Glass Dec 12 '13 at 20:25
  • 3
    This won't work for large numbers represented as strings. – None Apr 02 '15 at 17:22
  • numbers that exceed int values right? – naveen Apr 03 '15 at 06:07
  • Ok then try to parseInt some string with large number: parseInt('099999999999999999999');  // It may lead to really big issues and bugs that hard to find – Roman May 13 '20 at 14:09
  • @Roman updated the answer on why it doesn't work on large numbers – naveen May 15 '20 at 08:47
  • parseInt("0", 10) = 0. So if if by "remove leading zeros" you want an empty string in this case, you'll need to handle it explicitly. – Faust Aug 08 '21 at 06:37
  • Note that parseInt will throw away any decimals in the initial value. `parseInt("0123.02", 10) === 123` – Peet Feb 11 '22 at 11:27
253

regexp:

"014".replace(/^0+/, '')
keymone
  • 8,006
  • 1
  • 28
  • 33
26

It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

value = +value;

If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

input.value = +input.value;

is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • For some reasons, this is not working...See http://jsfiddle.net/8pYXH/ – copenndthagen Jul 13 '11 at 09:27
  • 2
    @hmthr: You did not assign a string to `x`, but a number. With a leading zero it will be interpreted as octal value. Print `x` and you will see that this value is already `13`. Using a string works: http://jsfiddle.net/fkling/8pYXH/1/ – Felix Kling Jul 13 '11 at 09:31
  • So finally will it still be a string ...I want the final value should be an integer... – copenndthagen Jul 13 '11 at 09:38
  • @hmthr: No. The value you get from field will be a string. After applying unary `+` it will be a number (as it is written in the documentation). See: http://jsfiddle.net/fkling/8pYXH/3/ – Felix Kling Jul 13 '11 at 09:47