最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS remove leading zeros - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question asked Mar 18, 2015 at 16:50 dannyhobbydannyhobby 231 silver badge3 bronze badges 3
  • possible duplicate of Truncate leading zeros of a string in Javascript – Simone Commented Mar 18, 2015 at 16:53
  • possible duplicate of Remove/ truncate leading zeros by javascript/jquery – Anwar Commented Mar 18, 2015 at 16:55
  • 3 This is not a duplicate, as it does something more than just truncating the non-mantisse part – axelduch Commented Mar 18, 2015 at 16:56
Add a ment  | 

2 Answers 2

Reset to default 5

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

发布评论

评论列表(0)

  1. 暂无评论