Phill Pafford
Phill Pafford

Reputation: 85348

Validate a number with grouped thousands with decimal to the hundreth

Looking for a simple way (Function/RegEx) to validate a number with grouped thousands.

Example Numbers:

.00 - 999.00 should validate
1,000.00 should validate
100,000.00 etc... should validate
100,000,000,000,000.00 should validate

Now I've seen the number_format(), but this formats the number not validates.

I wanted to use a RegEx but lost on how to do so.

preg_match(/^[\d]\,?\.[\d]{2}$/, $number);

but this doesn't work.

I've also looked at the money_format() but again this is format and not validation.

Upvotes: 1

Views: 212

Answers (3)

Robin
Robin

Reputation: 4260

If you've got a PHP5.3+ you could try the Intl number formatter:

http://www.php.net/manual/en/numberformatter.parse.php

Upvotes: 0

LukeH
LukeH

Reputation: 269498

^(?:\d{1,3}(?:,\d{3})*)?\.\d{2}$

Upvotes: 1

Turbotoast
Turbotoast

Reputation: 139

Just off the top of my head:

preg_match('%^[\d,]*\.\d{2}$%', $number);

This will match all of the numbers you mentioned (in fact: every string which starts with a combination of digits and commas and ends on "." and to digits).

Again, this is untested but should work.

Upvotes: 1

Related Questions