NumberLib.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. <?php
  2. App::uses('CakeNumber', 'Utility');
  3. /**
  4. * Extend CakeNumber with a few important improvements:
  5. * - config setting for format()
  6. * - spacer char for currency (initially from https://github.com/cakephp/cakephp/pull/1148)
  7. * - signed values possible
  8. *
  9. * 2011-03-07 ms
  10. */
  11. class NumberLib extends CakeNumber {
  12. protected static $_currency = 'EUR';
  13. protected static $_symbolRight = '€';
  14. protected static $_symbolLeft = '';
  15. protected static $_decimals = ',';
  16. protected static $_thousands = '.';
  17. /**
  18. * Correct the defaul values according to localization
  19. *
  20. * @return void
  21. */
  22. public static function config($options = array()) {
  23. $config = $options + (array)Configure::read('Localization');
  24. foreach ($config as $key => $value) {
  25. $key = '_' . $key;
  26. if (!isset(self::${$key})) {
  27. continue;
  28. }
  29. self::${$key} = $value;
  30. }
  31. }
  32. /**
  33. * Display price (or was price if available)
  34. * Without allowNegative it will always default all non-positive values to 0
  35. *
  36. * @param price
  37. * @param specialPrice (outranks the price)
  38. * @param options
  39. * - places
  40. * - allowNegative (defaults to false - price needs to be > 0)
  41. *
  42. * @deprecated use currency()
  43. * @return string
  44. * 2011-07-30 ms
  45. */
  46. public static function price($price, $specialPrice = null, $formatOptions = array()) {
  47. if ($specialPrice !== null && $specialPrice > 0) {
  48. $val = $specialPrice;
  49. } elseif ($price > 0 || !empty($formatOptions['allowNegative'])) {
  50. $val = $price;
  51. } else {
  52. if (isset($formatOptions['default'])) {
  53. return $formatOptions['default'];
  54. }
  55. $val = max(0, $price);
  56. }
  57. return self::money($val, $formatOptions);
  58. }
  59. /**
  60. * Convenience method to display the default currency
  61. *
  62. * @return string
  63. * 2011-10-05 ms
  64. */
  65. public static function money($amount, $formatOptions = array()) {
  66. return self::currency($amount, null, $formatOptions);
  67. }
  68. /**
  69. * format numeric values
  70. * should not be used for currencies
  71. *
  72. * @param float $number
  73. * @param int $places (0 = int, 1..x places after dec, -1..-x places before dec)
  74. * @param array $option : currency=true/false, ... (leave empty for no special treatment)
  75. * //TODO: automize per localeconv() ?
  76. * 2009-04-03 ms
  77. */
  78. public static function format($number, $formatOptions = array()) {
  79. if (!is_numeric($number)) {
  80. $default = '---';
  81. if (!empty($options['default'])) {
  82. $default = $options['default'];
  83. }
  84. return $default;
  85. }
  86. if ($formatOptions === false) {
  87. $formatOptions = array();
  88. } elseif (!is_array($formatOptions)) {
  89. $formatOptions = array('places' => $formatOptions);
  90. }
  91. $options = array('before' => '', 'after' => '', 'places' => 2, 'thousands' => self::$_thousands, 'decimals' => self::$_decimals, 'escape' => false);
  92. $options = array_merge($options, $formatOptions);
  93. if (!empty($options['currency'])) {
  94. if (!empty(self::$_symbolRight)) {
  95. $options['after'] = ' ' . self::$_symbolRight;
  96. } elseif (!empty(self::$_symbolLeft)) {
  97. $options['before'] = self::$_symbolLeft . ' ';
  98. }
  99. }
  100. /*
  101. if ($spacer !== false) {
  102. $spacer = ($spacer === true) ? ' ' : $spacer;
  103. if ((string)$before !== '') {
  104. $before .= $spacer;
  105. }
  106. if ((string)$after !== '') {
  107. $after = $spacer . $after;
  108. }
  109. }
  110. */
  111. if ($options['places'] < 0) {
  112. $number = round($number, $options['places']);
  113. }
  114. $sign = '';
  115. if ($number > 0 && !empty($options['signed'])) {
  116. $sign = '+';
  117. }
  118. if (isset($options['signed'])) {
  119. unset($options['signed']);
  120. }
  121. return $sign . parent::format($number, $options);
  122. }
  123. /**
  124. * Correct the default for European countries
  125. * 2012-04-08 ms
  126. */
  127. public static function currency($number, $currency = null, $formatOptions = array()) {
  128. if ($currency === null) {
  129. $currency = self::$_currency;
  130. }
  131. $defaults = array();
  132. if ($currency !== 'EUR' && isset(self::$_currencies[$currency])) {
  133. $defaults = self::$_currencies[$currency];
  134. } elseif ($currency !== 'EUR' && is_string($currency)) {
  135. $defaults['wholeSymbol'] = $currency;
  136. $defaults['wholePosition'] = 'before';
  137. $defaults['spacer'] = true;
  138. }
  139. $defaults += array(
  140. 'wholeSymbol' => '€', 'wholePosition' => 'after',
  141. 'negative' => '-', 'positive'=> '+', 'escape' => true,
  142. 'decimals' => ',', 'thousands' => '.',
  143. 'spacer' => $currency === 'EUR' ? true : false
  144. );
  145. $options = array_merge($defaults, $formatOptions);
  146. if (!empty($options['spacer'])) {
  147. $spacer = is_string($options['spacer']) ? $options['spacer'] : ' ';
  148. if ($options['wholePosition'] === 'after') {
  149. $options['wholeSymbol'] = $spacer . $options['wholeSymbol'];
  150. } elseif ($options['wholePosition'] === 'before') {
  151. $options['wholeSymbol'] .= $spacer;
  152. }
  153. }
  154. $sign = '';
  155. if ($number > 0 && !empty($options['signed'])) {
  156. $sign = $options['positive'];
  157. }
  158. return $sign . parent::currency($number, null, $options);
  159. }
  160. /**
  161. * Formats a number with a level of precision.
  162. *
  163. * @param float $number A floating point number.
  164. * @param integer $precision The precision of the returned number.
  165. * @param string $decimals
  166. * @return float Formatted float.
  167. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::precision
  168. */
  169. public static function precision($number, $precision = 3, $decimals = '.') {
  170. $number = parent::precision($number, $precision);
  171. if ($decimals !== '.' && $precision > 0) {
  172. $number = str_replace('.', $decimals, $number);
  173. }
  174. return $number;
  175. }
  176. /**
  177. * Returns a formatted-for-humans file size.
  178. *
  179. * @param integer $size Size in bytes
  180. * @return string Human readable size
  181. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize
  182. */
  183. public static function toReadableSize($size, $decimals = '.') {
  184. $size = parent::toReadableSize($size);
  185. if ($decimals !== '.') {
  186. $size = str_replace('.', $decimals, $size);
  187. }
  188. return $size;
  189. }
  190. /**
  191. * Formats a number into a percentage string.
  192. *
  193. * @param float $number A floating point number
  194. * @param integer $precision The precision of the returned number
  195. * @param string $decimals
  196. * @return string Percentage string
  197. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage
  198. */
  199. public static function toPercentage($number, $precision = 2, $decimals = '.') {
  200. return self::precision($number, $precision, $decimals) . '%';
  201. }
  202. /**
  203. * get the rounded average
  204. * @param array $values: int or float values
  205. * @param int $precision
  206. * @return int $average
  207. * 2009-09-05 ms
  208. */
  209. public static function average($values, $precision = 0) {
  210. $average = round(array_sum($values) / count($values), $precision);
  211. return $average;
  212. }
  213. /**
  214. * Round value
  215. *
  216. * @param float $number
  217. * @param float $increment
  218. * @return float $result
  219. * 2011-04-14 lb
  220. */
  221. public static function roundTo($number, $increments = 1.0) {
  222. $precision = self::getDecimalPlaces($increments);
  223. $res = round($number, $precision);
  224. if ($precision <= 0) {
  225. $res = (int)$res;
  226. }
  227. return $res;
  228. }
  229. /**
  230. * Round value up
  231. *
  232. * @param float $number
  233. * @param int $increment
  234. * @return float $result
  235. * 2011-04-14 lb
  236. */
  237. public static function roundUpTo($number, $increments = 1) {
  238. return (ceil($number / $increments) * $increments);
  239. }
  240. /**
  241. * Round value down
  242. *
  243. * @param float $number
  244. * @param int $increment
  245. * @return float $result
  246. * 2011-04-14 lb
  247. */
  248. public static function roundDownTo($number, $increments = 1) {
  249. return (floor($number / $increments) * $increments);
  250. }
  251. /**
  252. * Get decimal places
  253. *
  254. * @param float $number
  255. * @return int $decimalPlaces
  256. * 2011-04-15 lb
  257. */
  258. public static function getDecimalPlaces($number) {
  259. $decimalPlaces = 0;
  260. while ($number > 1 && $number != 0) {
  261. $number /= 10;
  262. $decimalPlaces -= 1;
  263. }
  264. while ($number < 1 && $number != 0) {
  265. $number *= 10;
  266. $decimalPlaces += 1;
  267. }
  268. return $decimalPlaces;
  269. }
  270. /**
  271. * Returns the English ordinal suffix (th, st, nd, etc) of a number.
  272. *
  273. * echo 2, Num::ordinal(2); // "2nd"
  274. * echo 10, Num::ordinal(10); // "10th"
  275. * echo 33, Num::ordinal(33); // "33rd"
  276. *
  277. * @param integer number
  278. * @return string
  279. */
  280. public static function ordinal($number) {
  281. if ($number % 100 > 10 and $number % 100 < 14) {
  282. return 'th';
  283. }
  284. switch ($number % 10) {
  285. case 1:
  286. return 'st';
  287. case 2:
  288. return 'nd';
  289. case 3:
  290. return 'rd';
  291. default:
  292. return 'th';
  293. }
  294. }
  295. /**
  296. * Can compare two float values
  297. *
  298. * @link http://php.net/manual/en/language.types.float.php
  299. * @param float $x
  300. * @param float $y
  301. * @param float $precision
  302. * @return boolean
  303. */
  304. public static function isFloatEqual($x, $y, $precision = 0.0000001) {
  305. return ($x + $precision >= $y) && ($x - $precision <= $y);
  306. }
  307. /**
  308. * Get the settings for a specific formatName
  309. *
  310. * @param string $formatName (EUR, ...)
  311. * @return array $currencySettings or null on failure
  312. */
  313. public static function getFormat($formatName) {
  314. if (!isset(self::$_currencies[$formatName])) {
  315. return null;
  316. }
  317. return self::$_currencies[$formatName];
  318. }
  319. }