Remove leading zeros from a number in Javascript [duplicate]
Asked Answered
H

3

194

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

Haskell answered 13/7, 2011 at 8:59 Comment(2)
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.Decanal
@felix. you already typed this as a comment :) +1 for that unary + didn't think of it.Inlier
I
310

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

Inlier answered 13/7, 2011 at 9:8 Comment(11)
It isn't clear from the question if it's ever the case, but this also removes anything after the decimal point.Robespierre
parseInt("08") == 0, it's a bug, use another answer.Grayson
@Greg. Thanks for the info. But I did not get the relevance. parseInt("08", 10) is indeed 8Inlier
might want to mention that the radix is important, so that people don't make the same mistake as greg.Angara
Heads up to anyone using this solution: Make sure you use the second parameter. parseInt("08") == 0, whereas parseInt("08",10) == 10Astrakhan
This won't work for large numbers represented as strings.Semen
numbers that exceed int values right?Inlier
Ok then try to parseInt some string with large number: parseInt('099999999999999999999'); // It may lead to really big issues and bugs that hard to findOutfitter
@Outfitter updated the answer on why it doesn't work on large numbersInlier
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.Ignatius
Note that parseInt will throw away any decimals in the initial value. parseInt("0123.02", 10) === 123Submerged
P
254

regexp:

"014".replace(/^0+/, '')
Prytaneum answered 13/7, 2011 at 9:0 Comment(5)
best solution, if you have a string like 012A (street number) this is the way to go. tySpelter
bad thing is it turns "0" into "" when the user would probably want to keep that one zero.Biography
@HermannIngjaldsson : for that negative lookahead canbe usedreplace(/^(?!0$)0+/, '')Vamoose
@PranavCBalan that is good, but what if the user inputs something like 00 or 000 and so on ?Lambertson
@Lambertson : for that, much more simple one using positive look-ahead assertion replace(/^0+(?=\d)/, '')Vamoose
D
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.

Decanal answered 13/7, 2011 at 9:2 Comment(4)
For some reasons, this is not working...See jsfiddle.net/8pYXHHaskell
@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: jsfiddle.net/fkling/8pYXH/1Decanal
So finally will it still be a string ...I want the final value should be an integer...Haskell
@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: jsfiddle.net/fkling/8pYXH/3Decanal

© 2022 - 2024 — McMap. All rights reserved.