[thelist] javascript numbers with decimals

Joshua Olson joshua at waetech.com
Tue May 6 20:34:02 CDT 2008

> -----Original Message-----
> From: Daniel Kessler
> Sent: Tuesday, May 06, 2008 10:36 AM

> Since you can enter in 544.44.44 with this, I might also have 
> a isNaN  
> check afterwards.  dunno if that is the best tactic, but clearly I  
> don't do a ton of work in js.

This is the crux.  We need a well designed regex if we really want to ensure
our input is good.  Sometimes it's better to check to see if the input
matches the format of what we expect, and then allow the user to fix the
information instead of trying to manipulate the provided information until
it matches what we expect (as the original code does).  

Ideally, the regex should include the minimum:

1.  Decimal is optional
2.  There can only be one decimal.
3.  If there is a decimal, there should be at least one digit after it.
4.  If we are going to allow negative numbers, then a - at the beginning
should be allowed.
5.  Leading zeros should not be allowed unless proceeded immediately by a
decimal point.
6.  Trailing zeros are ok.
7.  If there is a decimal, there should be at least one decimal after it.
8.  -0 should not be allowed

So, the general regex should match the above rules (except 8):


#8 is non-trivial to match, so I've excluded it.

Here's the regex broken down:

-? : the optional -
([1-9][0-9]*|0) : allows us only one of two options 
                  (explained below)
    [1-9][0-9]* : a single 1-9 followed by any number of 0-9.  
|                 This eliminates leading zeros.
    0 : indicates that we can also have a single 0 to the left 
        of the decimal
(\.[0-9]+)? : the entire decimal clause is optional, but 
              there will be exactly one decimal followed by 
              any number of 0-9 digits.



Joshua L. Olson
WAE Technologies, Inc.
Augusta, Georgia Web Design
Phone: 706.210.0168
Fax: 707.988.0168
Private Enterprise Number: 28752


Monitor bandwidth usage on IIS6 in real-time:

More information about the thelist mailing list