Coder Perfect

In Javascript, remove the leading zeros from an integer [duplicate]

Problem

In Javascript, what is the easiest and most cross-browser compatible approach to remove leading zeros from a number?

For example, if I enter 014 or 065 in a textbox, it should only return 14 or 65.

Asked by copenndthagen

Solution #1

For this conversion, we have four options.

The safest maximum number for the primitive type Number is 253-1(Number.MAX SAFE INTEGER).

Let’s look at the number string ‘099999999999999999999’ and see how we can convert it using the methods above.

All of the outcomes will be inaccurate.

This is because the numString value is bigger than Number when converted. MAX SAFE INTEGER. i.e.,

99999999999999999999 > 9007199254740991

This means that any operation that assumes the string may be transformed to a numeric type fails.

Primitive BigInt has recently been added for numbers bigger than 253. Check BigInthere’s browser compatibility.

This is how the conversion code will look.

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

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

Implementation will determine which radix is used. Although ECMAScript 5 recommends that 10 (decimal) be used, not all browsers currently support it.

As a result, when using parseInt, always give a radix.

Answered by naveen

Solution #2

regexp:

"014".replace(/^0+/, '')

Answered by keymone

Solution #3

Why you want to do this is unclear. You could use unary + [docs] to obtain the right numerical value:

value = +value;

Regex may be preferable if all you want to do is format the text. I’d say it depends on the values you’re dealing with. If all you have are integers,

input.value = +input.value;

is also acceptable. Of course, it works for float values as well, although depending on how many digits are after the point, converting it to a number and back to a string may remove some (at least for display).

Answered by Felix Kling

Post is based on https://stackoverflow.com/questions/6676488/remove-leading-zeros-from-a-number-in-javascript