NumberLib.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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 integer $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. * @return string
  76. */
  77. public static function format($number, $formatOptions = array()) {
  78. if (!is_numeric($number)) {
  79. $default = '---';
  80. if (!empty($options['default'])) {
  81. $default = $options['default'];
  82. }
  83. return $default;
  84. }
  85. if ($formatOptions === false) {
  86. $formatOptions = array();
  87. } elseif (!is_array($formatOptions)) {
  88. $formatOptions = array('places' => $formatOptions);
  89. }
  90. $options = array('before' => '', 'after' => '', 'places' => 2, 'thousands' => self::$_thousands, 'decimals' => self::$_decimals, 'escape' => false);
  91. $options = array_merge($options, $formatOptions);
  92. if (!empty($options['currency'])) {
  93. if (!empty(self::$_symbolRight)) {
  94. $options['after'] = ' ' . self::$_symbolRight;
  95. } elseif (!empty(self::$_symbolLeft)) {
  96. $options['before'] = self::$_symbolLeft . ' ';
  97. }
  98. }
  99. /*
  100. if ($spacer !== false) {
  101. $spacer = ($spacer === true) ? ' ' : $spacer;
  102. if ((string)$before !== '') {
  103. $before .= $spacer;
  104. }
  105. if ((string)$after !== '') {
  106. $after = $spacer . $after;
  107. }
  108. }
  109. */
  110. if ($options['places'] < 0) {
  111. $number = round($number, $options['places']);
  112. }
  113. $sign = '';
  114. if ($number > 0 && !empty($options['signed'])) {
  115. $sign = '+';
  116. }
  117. if (isset($options['signed'])) {
  118. unset($options['signed']);
  119. }
  120. return $sign . parent::format($number, $options);
  121. }
  122. /**
  123. * Correct the default for European countries
  124. *
  125. * @param mixed $number
  126. * @param string $currency
  127. * @param array $formatOptions
  128. * @return string
  129. */
  130. public static function currency($number, $currency = null, $formatOptions = array()) {
  131. if ($currency === null) {
  132. $currency = self::$_currency;
  133. }
  134. $defaults = array();
  135. if ($currency !== 'EUR' && isset(self::$_currencies[$currency])) {
  136. $defaults = self::$_currencies[$currency];
  137. } elseif ($currency !== 'EUR' && is_string($currency)) {
  138. $defaults['wholeSymbol'] = $currency;
  139. $defaults['wholePosition'] = 'before';
  140. $defaults['spacer'] = true;
  141. }
  142. $defaults += array(
  143. 'wholeSymbol' => '€', 'wholePosition' => 'after',
  144. 'negative' => '-', 'positive' => '+', 'escape' => true,
  145. 'decimals' => ',', 'thousands' => '.',
  146. 'spacer' => $currency === 'EUR' ? true : false
  147. );
  148. $options = array_merge($defaults, $formatOptions);
  149. if (!empty($options['spacer'])) {
  150. $spacer = is_string($options['spacer']) ? $options['spacer'] : ' ';
  151. if ($options['wholePosition'] === 'after') {
  152. $options['wholeSymbol'] = $spacer . $options['wholeSymbol'];
  153. } elseif ($options['wholePosition'] === 'before') {
  154. $options['wholeSymbol'] .= $spacer;
  155. }
  156. }
  157. $sign = '';
  158. if ($number > 0 && !empty($options['signed'])) {
  159. $sign = $options['positive'];
  160. }
  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 integer $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 integer $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 integer $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 = array()) {
  208. $options += array('multiply' => false, 'decimals' => '.');
  209. if ($options['multiply']) {
  210. $number *= 100;
  211. }
  212. return self::precision($number, $precision, $options['decimals']) . '%';
  213. }
  214. /**
  215. * Get the rounded average.
  216. *
  217. * @param array $values: int or float values
  218. * @param integer $precision
  219. * @return integer average
  220. */
  221. public static function average($values, $precision = 0) {
  222. $average = round(array_sum($values) / count($values), $precision);
  223. return $average;
  224. }
  225. /**
  226. * Round value.
  227. *
  228. * @param float $number
  229. * @param float $increment
  230. * @return float result
  231. */
  232. public static function roundTo($number, $increments = 1.0) {
  233. $precision = self::getDecimalPlaces($increments);
  234. $res = round($number, $precision);
  235. if ($precision <= 0) {
  236. $res = (int)$res;
  237. }
  238. return $res;
  239. }
  240. /**
  241. * Round value up.
  242. *
  243. * @param float $number
  244. * @param integer $increment
  245. * @return float result
  246. */
  247. public static function roundUpTo($number, $increments = 1) {
  248. return (ceil($number / $increments) * $increments);
  249. }
  250. /**
  251. * Round value down.
  252. *
  253. * @param float $number
  254. * @param integer $increment
  255. * @return float result
  256. */
  257. public static function roundDownTo($number, $increments = 1) {
  258. return (floor($number / $increments) * $increments);
  259. }
  260. /**
  261. * Get decimal places
  262. *
  263. * @param float $number
  264. * @return integer decimalPlaces
  265. */
  266. public static function getDecimalPlaces($number) {
  267. $decimalPlaces = 0;
  268. while ($number > 1 && $number != 0) {
  269. $number /= 10;
  270. $decimalPlaces -= 1;
  271. }
  272. while ($number < 1 && $number != 0) {
  273. $number *= 10;
  274. $decimalPlaces += 1;
  275. }
  276. return $decimalPlaces;
  277. }
  278. /**
  279. * Returns the English ordinal suffix (th, st, nd, etc) of a number.
  280. *
  281. * echo Num::ordinal(2); // "2nd"
  282. * echo Num::ordinal(10); // "10th"
  283. * echo Num::ordinal(33); // "33rd"
  284. *
  285. * @param integer $number
  286. * @return string
  287. */
  288. public static function ordinal($number) {
  289. if ($number % 100 > 10 && $number % 100 < 14) {
  290. return 'th';
  291. }
  292. switch ($number % 10) {
  293. case 1:
  294. return 'st';
  295. case 2:
  296. return 'nd';
  297. case 3:
  298. return 'rd';
  299. default:
  300. return 'th';
  301. }
  302. }
  303. /**
  304. * Can compare two float values
  305. *
  306. * @link http://php.net/manual/en/language.types.float.php
  307. * @param float $x
  308. * @param float $y
  309. * @param float $precision
  310. * @return boolean
  311. */
  312. public static function isFloatEqual($x, $y, $precision = 0.0000001) {
  313. return ($x + $precision >= $y) && ($x - $precision <= $y);
  314. }
  315. /**
  316. * Get the settings for a specific formatName
  317. *
  318. * @param string $formatName (EUR, ...)
  319. * @return array currencySettings or null on failure
  320. */
  321. public static function getFormat($formatName) {
  322. if (!isset(self::$_currencies[$formatName])) {
  323. return null;
  324. }
  325. return self::$_currencies[$formatName];
  326. }
  327. }