NumberLib.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 = []) {
  22. $config = $options + (array)Configure::read('Localization');
  23. foreach ($config as $key => $value) {
  24. $key = '_' . $key;
  25. if (!isset(static::${$key})) {
  26. continue;
  27. }
  28. static::${$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 = []) {
  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 static::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 = []) {
  65. return static::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 = []) {
  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 = [];
  86. } elseif (!is_array($formatOptions)) {
  87. $formatOptions = ['places' => $formatOptions];
  88. }
  89. $options = ['before' => '', 'after' => '', 'places' => 2, 'thousands' => static::$_thousands, 'decimals' => static::$_decimals, 'escape' => false];
  90. $options = $formatOptions + $options;
  91. if (!empty($options['currency'])) {
  92. if (!empty(static::$_symbolRight)) {
  93. $options['after'] = ' ' . static::$_symbolRight;
  94. } elseif (!empty(static::$_symbolLeft)) {
  95. $options['before'] = static::$_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 = []) {
  130. if ($currency === null) {
  131. $currency = static::$_currency;
  132. }
  133. $defaults = [];
  134. if ($currency !== 'EUR' && isset(static::$_currencies[$currency])) {
  135. $defaults = static::$_currencies[$currency];
  136. } elseif ($currency !== 'EUR' && is_string($currency)) {
  137. $defaults['wholeSymbol'] = $currency;
  138. $defaults['wholePosition'] = 'before';
  139. $defaults['spacer'] = true;
  140. }
  141. $defaults += [
  142. 'wholeSymbol' => '€', 'wholePosition' => 'after',
  143. 'negative' => '-', 'positive' => '+', 'escape' => true,
  144. 'decimals' => ',', 'thousands' => '.',
  145. 'spacer' => $currency === 'EUR' ? true : false
  146. ];
  147. $options = $formatOptions + $defaults;
  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. $options['signed'] = false;
  161. return $sign . parent::currency($number, null, $options);
  162. }
  163. /**
  164. * Formats a number with a level of precision.
  165. *
  166. * @param float $number A floating point number.
  167. * @param int $precision The precision of the returned number.
  168. * @param string $decimals
  169. * @return float Formatted float.
  170. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::precision
  171. */
  172. public static function precision($number, $precision = 3, $decimals = '.') {
  173. $number = parent::precision($number, $precision);
  174. if ($decimals !== '.' && $precision > 0) {
  175. $number = str_replace('.', $decimals, $number);
  176. }
  177. return $number;
  178. }
  179. /**
  180. * Returns a formatted-for-humans file size.
  181. *
  182. * @param int $size Size in bytes
  183. * @return string Human readable size
  184. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize
  185. */
  186. public static function toReadableSize($size, $decimals = '.') {
  187. $size = parent::toReadableSize($size);
  188. if ($decimals !== '.') {
  189. $size = str_replace('.', $decimals, $size);
  190. }
  191. return $size;
  192. }
  193. /**
  194. * Formats a number into a percentage string.
  195. *
  196. * Options:
  197. *
  198. * - `multiply`: Multiply the input value by 100 for decimal percentages.
  199. * - `decimals`: Decimal character.
  200. *
  201. * @param float $number A floating point number
  202. * @param int $precision The precision of the returned number
  203. * @param string $decimals
  204. * @return string Percentage string
  205. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage
  206. */
  207. public static function toPercentage($number, $precision = 2, $options = []) {
  208. $options += ['multiply' => false, 'decimals' => '.'];
  209. if ($options['multiply']) {
  210. $number *= 100;
  211. }
  212. return static::precision($number, $precision, $options['decimals']) . '%';
  213. }
  214. /**
  215. * Get the rounded average.
  216. *
  217. * @param array $values: int or float values
  218. * @param int $precision
  219. * @return float Average
  220. */
  221. public static function average($values, $precision = 0) {
  222. if (empty($values)) {
  223. return 0.0;
  224. }
  225. return round(array_sum($values) / count($values), $precision);
  226. }
  227. /**
  228. * Round value.
  229. *
  230. * @param float $number
  231. * @param float $increment
  232. * @return float result
  233. */
  234. public static function roundTo($number, $increments = 1.0) {
  235. $precision = static::getDecimalPlaces($increments);
  236. $res = round($number, $precision);
  237. if ($precision <= 0) {
  238. $res = (int)$res;
  239. }
  240. return $res;
  241. }
  242. /**
  243. * Round value up.
  244. *
  245. * @param float $number
  246. * @param int $increment
  247. * @return float result
  248. */
  249. public static function roundUpTo($number, $increments = 1) {
  250. return (ceil($number / $increments) * $increments);
  251. }
  252. /**
  253. * Round value down.
  254. *
  255. * @param float $number
  256. * @param int $increment
  257. * @return float result
  258. */
  259. public static function roundDownTo($number, $increments = 1) {
  260. return (floor($number / $increments) * $increments);
  261. }
  262. /**
  263. * Get decimal places
  264. *
  265. * @param float $number
  266. * @return int decimalPlaces
  267. */
  268. public static function getDecimalPlaces($number) {
  269. $decimalPlaces = 0;
  270. while ($number > 1 && $number != 0) {
  271. $number /= 10;
  272. $decimalPlaces -= 1;
  273. }
  274. while ($number < 1 && $number != 0) {
  275. $number *= 10;
  276. $decimalPlaces += 1;
  277. }
  278. return $decimalPlaces;
  279. }
  280. /**
  281. * Returns the English ordinal suffix (th, st, nd, etc) of a number.
  282. *
  283. * echo NumberLib::ordinal(2); // "nd"
  284. * echo NumberLib::ordinal(10); // "th"
  285. * echo NumberLib::ordinal(33); // "rd"
  286. *
  287. * @param int $number
  288. * @return string
  289. */
  290. public static function ordinal($number) {
  291. if ($number % 100 > 10 && $number % 100 < 14) {
  292. return 'th';
  293. }
  294. switch ($number % 10) {
  295. case 1:
  296. return 'st';
  297. case 2:
  298. return 'nd';
  299. case 3:
  300. return 'rd';
  301. default:
  302. return 'th';
  303. }
  304. }
  305. /**
  306. * Can compare two float values
  307. *
  308. * @link http://php.net/manual/en/language.types.float.php
  309. * @param float $x
  310. * @param float $y
  311. * @param float $precision
  312. * @return bool
  313. */
  314. public static function isFloatEqual($x, $y, $precision = 0.0000001) {
  315. return ($x + $precision >= $y) && ($x - $precision <= $y);
  316. }
  317. /**
  318. * Get the settings for a specific formatName
  319. *
  320. * @param string $formatName (EUR, ...)
  321. * @return array currencySettings or null on failure
  322. */
  323. public static function getFormat($formatName) {
  324. if (!isset(static::$_currencies[$formatName])) {
  325. return null;
  326. }
  327. return static::$_currencies[$formatName];
  328. }
  329. }