What is the regular expression for a decimal with a precision of 2?
Valid examples:
123.12
2
56754
92929292929292.12
0.21
3.1
^[0-9]+(\.([0-9]{1,2})?)?$
Will make things like 12.
accepted. This is not what is commonly accepted but if in case you need to be “flexible”, that is one way to go. And of course [0-9]
can be replaced with \d
, but I guess it’s more readable this way.
To include an optional minus sign and to disallow numbers like 015
(which can be mistaken for octal numbers) write:
-?(0|([1-9]\d*))(\.\d+)?
Won't you need to take the e
in e666.76
into account?
With
(e|0-9)\d*\d.\d{1,2)
Main answer is WRONG because it valids 5.
or 5,
inputs
this code handle it (but in my example negative numbers are forbidden):
/^[0-9]+([.,][0-9]{1,2})?$/;
results are bellow:
true => "0" / true => "0.00" / true => "0.0" / true => "0,00" / true => "0,0" / true => "1,2" true => "1.1"/ true => "1" / true => "100" true => "100.00"/ true => "100.0" / true => "1.11" / true => "1,11"/ false => "-5" / false => "-0.00" / true => "101" / false => "0.00.0" / true => "0.000" / true => "000.25" / false => ".25" / true => "100.01" / true => "100.2" / true => "00" / false => "5." / false => "6," / true => "82" / true => "81,3" / true => "7" / true => "7.654"
function DecimalNumberValidation() {
var amounttext = ;
if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
alert('Please enter only numbers into amount textbox.')
}
else
{
alert('Right Number');
}
}
function will validate any decimal number weather number has decimal places or not, it will say "Right Number" other wise "Please enter only numbers into amount textbox." alert message will come up.
Thanks... :)
I use this one for up to two decimal places:
(^(\+|\-)(0|([1-9][0-9]*))(\.[0-9]{1,2})?$)|(^(0{0,1}|([1-9][0-9]*))(\.[0-9]{1,2})?$)
passes:
.25
0.25
10.25
+0.25
doesn't pass:
-.25
01.25
1.
1.256