Skip to content

Instantly share code, notes, and snippets.

@iksi
Created December 23, 2014 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iksi/cd4aedfcfd5a98971641 to your computer and use it in GitHub Desktop.
Save iksi/cd4aedfcfd5a98971641 to your computer and use it in GitHub Desktop.
Price to float
// Returns False if no number given, number before decimal is
// missing and when the decimal shorter than two digits
function price_to_float($string)
{
// Remove leading and trailing whitespace
$string = trim($string);
// Check for decimal with comma first
if ( (bool) preg_match('/[+-]?[0-9]\,[0-9]{2}(\w|\b)/D', $string))
{
// Decimal with a comma
return number_format(filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT) / 100, 2, '.', '');
}
if ( (bool) preg_match('/[+-]?[0-9]\.[0-9]{2}(\w|\b)/D', $string))
{
// Decimal with a dot
return filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
}
if ( ! preg_match('/[\.,]/', $string) && ! ctype_alpha($string))
{
return number_format(filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT), 2, '.', '');
}
return FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment