Created
December 23, 2014 12:39
-
-
Save iksi/cd4aedfcfd5a98971641 to your computer and use it in GitHub Desktop.
Price to float
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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