Created
December 18, 2014 14:46
-
-
Save nWidart/9338683a71f46f66e32c to your computer and use it in GitHub Desktop.
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
<?php | |
class NUMBERS | |
{ | |
/** | |
* Determine if numer is a float even when placed in a string. Bases type on a foreknown decimal length | |
* @param $num | |
* @param int $decimals | |
* @return bool | |
*/ | |
public static function isFloat($num, $decimals = 2) | |
{ | |
if(stristr($num, ',') && stristr($num, '.')) | |
{ | |
return true; | |
} | |
elseif(stristr($num, ',')) | |
{ | |
$separator = ','; | |
} | |
elseif(stristr($num, '.')) | |
{ | |
$separator = '.'; | |
} | |
if(isset($separator)) | |
{ | |
if(substr_count($num, $separator) > 1)//if it's a decimal separator, there can be only one ;) | |
return false; | |
$end = end(explode($separator, $num)); | |
if(strlen($end) == $decimals) | |
return true; | |
} | |
return false; | |
} | |
/** | |
* Normalize number with unknown original locale formatting to default formatting. Assumes foreknown decimal length | |
* @param $num | |
* @param int $decimals | |
* @return float|int | |
*/ | |
public static function normalize($num, $decimals = 2) | |
{ | |
$num = preg_replace('/\s+/', '', $num); | |
if(self::isFloat($num, $decimals)) | |
{ | |
$separator = self::getDecimalSeparator($num, $decimals); | |
if($separator == '.') | |
{ | |
return floatval(str_replace(',', '', $num)); | |
} | |
else | |
{ | |
return floatval(str_replace(',', '.', str_replace('.', '', $num))); | |
} | |
} | |
else | |
{ | |
return intval(str_replace([',', '.'], '', $num)); | |
} | |
} | |
/** | |
* Input assumes a float in string. Returns the last separator in the string, based on the decimal length | |
* @param float|string $num | |
* @param int $decimals | |
* @return string | |
*/ | |
public static function getDecimalSeparator($num, $decimals = 2) | |
{ | |
return substr($num, strlen($num) - $decimals - 1, 1); | |
} | |
/** | |
* Greedy check for numeric values in a string. If the string could be interpreted as numeric it returns true | |
* @param $num | |
* @return int | |
*/ | |
public static function isNumeric($num) | |
{ | |
return preg_match('/(\d+)(((.|,)\d+)+)?/', $num); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment