Advertisement
Guest User

Untitled

a guest
Dec 18th, 2014
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. <?php
  2.  
  3. class NUMBERS
  4. {
  5. /**
  6. * Determine if numer is a float even when placed in a string. Bases type on a foreknown decimal length
  7. * @param $num
  8. * @param int $decimals
  9. * @return bool
  10. */
  11. public static function isFloat($num, $decimals = 2)
  12. {
  13. if(stristr($num, ',') && stristr($num, '.'))
  14. {
  15. return true;
  16. }
  17. elseif(stristr($num, ','))
  18. {
  19. $separator = ',';
  20. }
  21. elseif(stristr($num, '.'))
  22. {
  23. $separator = '.';
  24. }
  25.  
  26. if(isset($separator))
  27. {
  28. if(substr_count($num, $separator) > 1)//if it's a decimal separator, there can be only one ;)
  29. return false;
  30.  
  31. $end = end(explode($separator, $num));
  32.  
  33. if(strlen($end) == $decimals)
  34. return true;
  35. }
  36.  
  37.  
  38. return false;
  39. }
  40.  
  41. /**
  42. * Normalize number with unknown original locale formatting to default formatting. Assumes foreknown decimal length
  43. * @param $num
  44. * @param int $decimals
  45. * @return float|int
  46. */
  47. public static function normalize($num, $decimals = 2)
  48. {
  49. $num = preg_replace('/\s+/', '', $num);
  50.  
  51. if(self::isFloat($num, $decimals))
  52. {
  53. $separator = self::getDecimalSeparator($num, $decimals);
  54. if($separator == '.')
  55. {
  56. return floatval(str_replace(',', '', $num));
  57. }
  58. else
  59. {
  60. return floatval(str_replace(',', '.', str_replace('.', '', $num)));
  61. }
  62. }
  63. else
  64. {
  65. return intval(str_replace([',', '.'], '', $num));
  66. }
  67. }
  68.  
  69. /**
  70. * Input assumes a float in string. Returns the last separator in the string, based on the decimal length
  71. * @param float|string $num
  72. * @param int $decimals
  73. * @return string
  74. */
  75. public static function getDecimalSeparator($num, $decimals = 2)
  76. {
  77. return substr($num, strlen($num) - $decimals - 1, 1);
  78. }
  79.  
  80. /**
  81. * Greedy check for numeric values in a string. If the string could be interpreted as numeric it returns true
  82. * @param $num
  83. * @return int
  84. */
  85. public static function isNumeric($num)
  86. {
  87. return preg_match('/(\d+)(((.|,)\d+)+)?/', $num);
  88. }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement