Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jul 2004
    Thanked 0 Times in 0 Posts

    regular expression for price

    Ok i need a good regular expression to check for a price format. Price looks like:

    65.50 or 65

    decimal is optional. Anyone know?

  2. #2
    Regular Coder ralph l mayo's Avatar
    Join Date
    Nov 2005
    Thanked 31 Times in 29 Posts
    I think this works, it may not be the best: ^[0-9]+(\.[0-9]{2})?$
    (translation: from the beginning (^) match only numbers for however many there are, at least one, optionally followed by a group containing a decimal and two more numbers before the end of the string ($))
    Last edited by ralph l mayo; 04-25-2006 at 04:33 AM.

  3. #3
    Administrator chump2877's Avatar
    Join Date
    Dec 2004
    the U.S. of freakin' A.
    Thanked 176 Times in 167 Posts
    this also works:

    reg = /^\d+(\.\d{2})?$/;

    I see you beat me to it Ralph!

    Edit: just to see how it works wth different numbers:

    <script type="text/javascript">
    var string = new Array();
    string[1] = "109.50";
    string[2] = "19.50";
    string[3] = "0.50";
    string[4] = "19";
    string[5] = "9.0.7";
    string[6] = "word";
    string[7] = "9.7";
    string[8] = ".45";
    reg = /^\d+(\.\d{2})?$/;
    for (x=1; x<=8; x++)
    	if (reg.test(string[x]))
    		document.write(string[x]+' is a valid price.<br>');
    		document.write(string[x]+' is NOT a valid price.<br>');

    109.50 is a valid price.
    19.50 is a valid price.
    0.50 is a valid price.
    19 is a valid price.
    9.0.7 is NOT a valid price.
    word is NOT a valid price.
    9.7 is NOT a valid price.
    .45 is NOT a valid price.
    Last edited by chump2877; 04-25-2006 at 05:28 AM.
    Regards, R.J.


    Help spread the word! Like my YouTube-to-Mp3 Conversion Script on Facebook !! :-)
    [Instructional videos and tutorials are also available on YouTube, Dailymotion, and Vimeo]
    Get free updates about new software version releases, features, and bug fixes!
    ♪♪ …Need Web Hosting For My YouTube-To-Mp3 Conversion Software? Check Here !!… ♪♪


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts