Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

javascript - Regular expression to enforce 2 digits after decimal point

I need to validate a numeric string with JavaScript, to ensure the number has exactly two decimal places.

The validation will pass only if

  1. the number has precisely two decimal places
  2. there is at least one digit before the decimal point. (could be zero)
  3. the number before the decimal point can not begin with more than one zero.

Valid numbers:

0.01
0.12
111.23
1234.56
012345.67
123.00
0.00

Invalid numbers:

.12
1.1
0.0
00.00
1234.
1234.567
1234
00123.45
abcd.12
12a4.56
1234.5A

I have tried the regular expression [0-9][.][0-9][0-9]$, but it allows letters before decimal point like 12a4.56.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

. matches any character, it does not do what you think it does. You have to escape it. Also, you have two more errors; try

^[0-9]+.[0-9][0-9]$

instead, or even better, use d for decimal digits:

^d+.dd$

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...