Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?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);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement