[英]JS remove leading zeros
In JavaScript, I want to remove the decimal place & the following zeros. 在JavaScript中,我要删除小数位和以下零。
For example, my original number: "0.00558", I want to be left with "558". 例如,我原来的数字:“ 0.00558”,我想留下“ 558”。
Is this possible? 这可能吗? (I'm also using AngularJS if that has a method for this).
(我也使用AngularJS,如果有此方法的话)。
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. 虽然我总是将默认基数设置为10,但是@aduch很有意义。 And MDN concurs.
MDN也同意。
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. 来自MDN:如果输入字符串以“ 0x”或“ 0X”开头,则基数为16(十六进制),并且将解析字符串的其余部分。 If the input string begins with "0", radix is eight (octal) or 10 (decimal).
如果输入字符串以“ 0”开头,则基数为8(八进制)或10(十进制)。 Exactly which radix is chosen is implementation-dependent.
选择哪个基数取决于实现。 ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.
ECMAScript 5指定使用10(十进制),但并非所有浏览器都支持。 For this reason always specify a radix when using parseInt.
因此,在使用parseInt时始终指定一个基数。 If the input string begins with any other value, the radix is 10 (decimal).
如果输入字符串以任何其他值开头,则基数为10(十进制)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.