Hello and welcome to our community! Is this your first visit?
Register
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
    Posts
    11
    Thanks
    0
    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
    Regular Coder ralph l mayo's Avatar
    Join Date
    Nov 2005
    Posts
    951
    Thanks
    1
    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 03:33 AM.

  • #3
    Senior Coder chump2877's Avatar
    Join Date
    Dec 2004
    Location
    the U.S. of freakin' A.
    Posts
    2,778
    Thanks
    19
    Thanked 155 Times in 146 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:

    Code:
    <HTML>
    <HEAD>
    <TITLE></TITLE>
    </HEAD>
    
    <BODY>
    
    
    <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>');
    	}
    	else
    	{
    		document.write(string[x]+' is NOT a valid price.<br>');
    	}
    }
    
    -->
    </script>
    
    
    </BODY>
    </HTML>
    returns:

    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 04:28 AM.
    Regards, R.J.

    ---------------------------------------------------------

    Help spread the word! Like my YouTube-to-Mp3 Conversion Script on Facebook !! :)
    [Related videos and tutorials are also available at my YouTube channel and on Dailymotion]
    Get free updates about new software version releases, features, and bug fixes!


  •  

    Posting Permissions

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