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
 |  Show 3 more ments

5 Answers 5

Reset to default 4

v = 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