2

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

dannyhobby
  • 23
  • 1
  • 3
  • possible duplicate of [Truncate leading zeros of a string in Javascript](http://stackoverflow.com/questions/594325/truncate-leading-zeros-of-a-string-in-javascript) – Simone Mar 18 '15 at 16:53
  • possible duplicate of [Remove/ truncate leading zeros by javascript/jquery](http://stackoverflow.com/questions/8276451/remove-truncate-leading-zeros-by-javascript-jquery) – Anwar Mar 18 '15 at 16:55
  • 3
    This is not a duplicate, as it does something more than just truncating the non-mantisse part – axelduch Mar 18 '15 at 16:56

2 Answers2

4

you can do that by a simple regex replace.

var number = "0.00558";
number = number.replace(/^[0\.]+/, "");
console.log(number);//number is now "558"
Austin Mullins
  • 7,307
  • 2
  • 33
  • 48
Jerry
  • 938
  • 7
  • 13
1

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

Misunderstood
  • 5,534
  • 1
  • 18
  • 25