Question

I'm looking for a good way to check a number that a user has entered for correct position of optional commas.

For example

1,000,000.00 = correct
1000000      = correct
1,00,000.00  = incorrect
,100,000     = incorrect

So it looks like I need to check to see that there is at least one number to the left and 3 numbers to the right of the comma, or is there a RegEx way to do this?

Was it helpful?

Solution

What are you going to use this for? Or put another way, why care? Why not just strip out all commas and convert it to a numeric type?

OTHER TIPS

/^(?:\d+|\d{1,3}(?:,\d{3})*)(?:\.\d+)?$/

Check out this website: http://blog.stevenlevithan.com/archives/commafy-numbers

Here's the code snippet:

String.prototype.commafy = function () {
    return this.replace(/(^|[^\w.])(\d{4,})/g, function($0, $1, $2) {
        return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,");
    });
}

Number.prototype.commafy = function () {
    return String(this).commafy();
}

What you can do is replace all commas and then use this code to add in the commas yourself.

Hope that helps.

Here’s a pattern that answers your question. There are also many other number-related patterns there, including ones that are maintainable — something no one ever seems to worry about.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top