NumberLib.php 9.1 KB

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