Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
189
rated 0 times [  196] [ 7]  / answers: 1 / hits: 51075  / 12 Years ago, sat, november 3, 2012, 12:00:00

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.


More From » regex

 Answers
32

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

[#82218] Thursday, November 1, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
levidaylonj

Total Points: 392
Total Questions: 100
Total Answers: 112

Location: Bahrain
Member since Fri, Sep 16, 2022
2 Years ago
;