简体   繁体   中英

JS remove leading zeros

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).

you can do that by a simple regex replace.

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM