Find if string is a valid float

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Find if string is a valid float

Post 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
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post 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)
Post Reply