JS remove leading zeros

后端 未结 2 589
南旧
南旧 2021-01-23 10:52

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 thi

2条回答
  •  情话喂你
    2021-01-23 11:35

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

提交回复
热议问题