admin管理员组文章数量:1400566
I need to alter users input and leave in the box only integer or decimal values, i.e. 4567 or 354.5635. I use the following statement:
v = v.replace(/[^\d\.]+/g, "");
But this allows multiple decimal points such as 345.45.345.67. How do I ensure that only one point is there?
I need to alter users input and leave in the box only integer or decimal values, i.e. 4567 or 354.5635. I use the following statement:
v = v.replace(/[^\d\.]+/g, "");
But this allows multiple decimal points such as 345.45.345.67. How do I ensure that only one point is there?
Share Improve this question edited Nov 15, 2011 at 16:39 Lightness Races in Orbit 386k77 gold badges666 silver badges1.1k bronze badges asked Nov 15, 2011 at 16:26 KizzKizz 7971 gold badge10 silver badges16 bronze badges 8- If this is about the more general problem of checking if a string is numerical, regular expressions are not the best way - look here: stackoverflow./questions/18082/… – wutz Commented Nov 15, 2011 at 16:38
- Why did you e to the conclusion that you need regular expressions here? – Lightness Races in Orbit Commented Nov 15, 2011 at 16:40
-
So if the user inputs
"5.5.5"
or"5.5abc"
what should happen? – Šime Vidas Commented Nov 15, 2011 at 16:47 - @Tomalak: it was kind of "obvious" :) Do I? – Kizz Commented Nov 15, 2011 at 16:53
- 1 @Kizz I've created this question to solve your issue: stackoverflow./questions/8140612/… – Šime Vidas Commented Nov 15, 2011 at 23:03
5 Answers
Reset to default 4v = parseFloat(v).toFixed(numberOfDecimalDigits);
Not sure if JS can do lookahead assertions, but if it can it could be done with a regex IF JS can also do reverse(input_string).
A reverse is needed because you want to allow the FIRST dot, and take out the rest.
However, search progresses left to right.
/(?:[.](?=.*[.])|[^\d.])+/g
will take out all but the last '.'
So, the string has to be reversed, substituted, then reversed again.
Perl code example:
my $ss = 'asdf45.980.765';
$ss = reverse $ss;
$ss =~ s/(?:[.](?=.*[.])|[^\d.])+//g;
$ss = reverse $ss;
print $ss;
Output: 45.980765
v = v.replace(/[A-Za-z$-]/g, "");
// This will replace the alphabets
v = v.replace(/[^\d]*(\d+(\.\d+)?)?.*/g, "$1");
// This will replace other then decimal
I'd remend to use parseFloat
here:
v = parseFloat(v);
This will guarantee you to have integer/decimal value or NaN
.
v = v.replace(/[^\d]*(\d+(\.\d+)?)?.*/g, "$1");
本文标签: javascriptHow to remove extra decimal pointsStack Overflow
版权声明:本文标题:javascript - How to remove extra decimal points? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744768228a2624174.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论