## Friday, March 16, 2012

### Decimal / Floating point number validation using javascript / jQuery (regular expression)

To validate any decimal number

function validateDecimal(value)    {
var RE = /^\d*\.?\d*\$/;
if(RE.test(value)){
return true;
}else{
return false;
}
}

Eg: 54     -> true
1.235  -> true
12.258 -> true
1.2.5  -> false
sdf123 -> false

To validate decimal number with two digit precision

function validateDecimal(value)    {
var RE = /^\d*(\.\d{1})?\d{0,1}\$/;
if(RE.test(value)){
return true;
}else{
return false;
}
}

Eg: 54     -> true
5.2       -> true
1.23   -> true
155.89 -> true
12.258 -> false
1.2.5  -> false
sdf123 -> false

General form of regular expression for decimal a number

^\d{0,M}(\.\d{1})?\d{0,N}\$

M = at most number of digits before decimal point.
N = (n-1); n = at most number of digits after decimal point.

1. Very nice and very eassy.. great

2. Thanks alot...very simple method

3. 4. Thanks Buddy......

5. you are the man!!! the best I have seen so far!!

6. its accepting 1. also it should not

1. You are correct @Saidesh, I have fixed the bug and upaded. Thanks for pointing out.

7. where to call the function in the html page?please suggest. I have done like

input class="form-control" title="Please ensure your entering amount in Lakhs/Crores" type="number" name="loan_amount" id="loanamount" onkeyup="validateDecimal(this)" required min="1" step="0.01" tabindex="1" placeholder="Please Enter Loan amount"

8. Negative decimals are not acceptetd.
Take this :-)

var RE = /^[-+]?\d*(\.\d{1})?\d{0,1}\$/;

9. how to pass parameter in regular expression

10. Great Thanks

11. 12. thank you for validating floating point value

13. thank you for help to validate float point value