Page 1 of 1

Find if string is a valid float

Posted: Sun May 20, 2007 6:58 pm
by Stryks
This is related to a Previous Thread

Just wanted to get an opinion of the following regex for checking a string against a comma separated float value.

Code: Select all

<?php
$test = array("123", "123.45", "one.34", "123.45.67", "one", 12.52, "", "1,234.50", "1,234,567.89", "1,23");

foreach ($test as $test_val) {
	echo "<br>Is $test_val valid? ";
	if(isFloat($test_val)) echo " Yes"; else echo "No";
}

function isFloat($value) {
	return preg_match('/\A[\d]*(?:[,]{1}[\d]{3})*(?:[.]{1}[\d]*)?\z/', $value);
}

?>
I'm using this as a part of a form validation process, so it's important that it's blocking properly. At the moment I'm a little stuck with how to make it allow .12 and 12 and not allow an empty string.

Any ideas? Any suggestions for making this better?

Cheers

Posted: Sun May 20, 2007 7:37 pm
by Stryks
Maybe this is a better option, though part of me is wondering about the last part and the first part both being matched, but it seems to work regardless.

I really am kinda flying blind here.

I'd just like to know I can really depend on this.

Code: Select all

preg_match('/\A(?:[\d]{0,3}(?:[,]{1}[\d]{3})*(?:[.]{1}[\d]*|[\d]+){1})\z/', $value)