JS remove leading zeros

2020-04-21 00:25发布

问题:

In JavaScript, I want to remove the decimal place & the following zeros.

For example, my original number: "0.00558", I want to be left with "558".

Is this possible? (I'm also using AngularJS if that has a method for this).

回答1:

you can do that by a simple regex replace.

var number = "0.00558";
number = number.replace(/^[0\.]+/, "");
console.log(number);//number is now "558"


回答2:

Remove the decimal point:

el.value.replace(/[^\d]/g,'');

or

el.value.replace(/\./g,'');

Then get the integer value:

var el.value = parseInt(el.value);

While I have always gone with the default radix being 10, @aduch makes a good point. And MDN concurs.

The safer way is:

var el.value = parseInt(el.value,10);

From MDN: 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).