Reputation: 1497
I need to validate a numeric string with JavaScript, to ensure the number has exactly two decimal places.
The validation will pass only if
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
.
Upvotes: 5
Views: 57242
Reputation: 761
Try This Code
pattern="[0-9]*(\.?[0-9]{1,2}$)?"
1 Valid
1.1 Valid
1.12 Valid
1.123 not Valid
only number Valid
pattern="[0-9]*(.?[0-9]{2}$)?"
1 Valid
1.1 not Valid
1.12 Valid
1.123 not Valid
only number Valid
Upvotes: 0
Reputation: 31
i used this
^[1-9][1-9]*[.]?[1-9]{0,2}$
0 not accept
123.12 accept but 123.123 not accept
1 accept
12213123 accept
sdfsf not accept
15.12 accept
15@12 not accept
15&12 not accept
Upvotes: 3
Reputation: 16905
^(0|0?[1-9]\d*)\.\d\d$
\.\d\d$
The other two conditions can be restated as follows:
This is covered in these two cases:
0
0?[1-9]\d*
Upvotes: 7
Reputation: 168853
You don't need regular expressions for this.
JavaScript has a function toFixed()
that will do what you need.
var fixedtotwodecimals = floatvalue.toFixed(2);
Upvotes: 4
Reputation:
.
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+\.\d\d$
Upvotes: 8
Reputation: 5356
var values='0.12';
document.write(values.match(/\d+[.]+\d+\d/));
change value as you want and check it
Upvotes: 1