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.

14 comments:

  1. Very nice and very eassy.. great

    ReplyDelete
  2. Thanks alot...very simple method

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

    ReplyDelete
  4. its accepting 1. also it should not

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

      Delete
  5. 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"

    ReplyDelete
  6. Negative decimals are not acceptetd.
    Take this :-)

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

    ReplyDelete
  7. how to pass parameter in regular expression

    ReplyDelete
  8. thank you for validating floating point value

    ReplyDelete
  9. thank you for help to validate float point value

    ReplyDelete