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

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...