Jump to content

Identifying a formatted number string (e.g. 5,700) as a number


deane034

Recommended Posts

Hi,

 

Does anyone know how to :

 

 

1) Recognize a formatted number string such as 5,700.99 as a float number.  That is a function which returns true of it's a formatted number and false if it's a general string e.g. "some string"

 

2) Convert that formatted number into a numeric float.

 

What I'm looking for essentially is a reverse for the PHP number_format function. Which does the opposite.

 

Any ideas?

thanks.

Wrote a function using number_format():

 

<?php
function is_number_format($number, $dec_point = '.', $thousands_sep = ',') {
$numeric = str_replace($thousands_sep, '', $number);
$parts = explode($dec_point, $numeric);
$dec = strlen(end($parts));
if ($dec_point != '.') {
	$numeric = str_replace($dec_point, '.', $numeric);
}
if ($number == number_format((float) $numeric, $dec, $dec_point, $thousands_sep)) {
	return true;
} else {
	return false;
}
}

//test
$n = '5,700.99';
if (is_number_format($n)) {
echo "$n is a formatted number!";
}
?>

 

Seems to work fine. Just pass the second and third parameter if the dec. point and thousands sep. are different from a dot and a comma.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.