Number.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 0.10.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Utility;
  16. use Cake\Error\Exception;
  17. /**
  18. * Number helper library.
  19. *
  20. * Methods to make numbers more readable.
  21. *
  22. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html
  23. */
  24. class Number {
  25. /**
  26. * Currencies supported by the helper. You can add additional currency formats
  27. * with Cake\Utility\Number::addFormat
  28. *
  29. * @var array
  30. */
  31. protected static $_currencies = array(
  32. 'AUD' => array(
  33. 'wholeSymbol' => '$', 'wholePosition' => 'before', 'fractionSymbol' => 'c', 'fractionPosition' => 'after',
  34. 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
  35. 'fractionExponent' => 2
  36. ),
  37. 'CAD' => array(
  38. 'wholeSymbol' => '$', 'wholePosition' => 'before', 'fractionSymbol' => 'c', 'fractionPosition' => 'after',
  39. 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
  40. 'fractionExponent' => 2
  41. ),
  42. 'USD' => array(
  43. 'wholeSymbol' => '$', 'wholePosition' => 'before', 'fractionSymbol' => 'c', 'fractionPosition' => 'after',
  44. 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
  45. 'fractionExponent' => 2
  46. ),
  47. 'EUR' => array(
  48. 'wholeSymbol' => '€', 'wholePosition' => 'before', 'fractionSymbol' => false, 'fractionPosition' => 'after',
  49. 'zero' => 0, 'places' => 2, 'thousands' => '.', 'decimals' => ',', 'negative' => '()', 'escape' => true,
  50. 'fractionExponent' => 0
  51. ),
  52. 'GBP' => array(
  53. 'wholeSymbol' => '£', 'wholePosition' => 'before', 'fractionSymbol' => 'p', 'fractionPosition' => 'after',
  54. 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
  55. 'fractionExponent' => 2
  56. ),
  57. 'JPY' => array(
  58. 'wholeSymbol' => '¥', 'wholePosition' => 'before', 'fractionSymbol' => false, 'fractionPosition' => 'after',
  59. 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
  60. 'fractionExponent' => 0
  61. ),
  62. );
  63. /**
  64. * Default options for currency formats
  65. *
  66. * @var array
  67. */
  68. protected static $_currencyDefaults = array(
  69. 'wholeSymbol' => '', 'wholePosition' => 'before', 'fractionSymbol' => false, 'fractionPosition' => 'after',
  70. 'zero' => '0', 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
  71. 'fractionExponent' => 2
  72. );
  73. /**
  74. * Default currency used by Number::currency()
  75. *
  76. * @var string
  77. */
  78. protected static $_defaultCurrency = 'USD';
  79. /**
  80. * If native number_format() should be used. If >= PHP5.4
  81. *
  82. * @var bool
  83. */
  84. protected static $_numberFormatSupport = null;
  85. /**
  86. * Formats a number with a level of precision.
  87. *
  88. * @param float $value A floating point number.
  89. * @param int $precision The precision of the returned number.
  90. * @return float Formatted float.
  91. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::precision
  92. */
  93. public static function precision($value, $precision = 3) {
  94. return sprintf("%01.{$precision}f", $value);
  95. }
  96. /**
  97. * Returns a formatted-for-humans file size.
  98. *
  99. * @param int $size Size in bytes
  100. * @return string Human readable size
  101. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize
  102. */
  103. public static function toReadableSize($size) {
  104. switch (true) {
  105. case $size < 1024:
  106. return __dn('cake', '%d Byte', '%d Bytes', $size, $size);
  107. case round($size / 1024) < 1024:
  108. return __d('cake', '%s KB', static::precision($size / 1024, 0));
  109. case round($size / 1024 / 1024, 2) < 1024:
  110. return __d('cake', '%s MB', static::precision($size / 1024 / 1024, 2));
  111. case round($size / 1024 / 1024 / 1024, 2) < 1024:
  112. return __d('cake', '%s GB', static::precision($size / 1024 / 1024 / 1024, 2));
  113. default:
  114. return __d('cake', '%s TB', static::precision($size / 1024 / 1024 / 1024 / 1024, 2));
  115. }
  116. }
  117. /**
  118. * Converts filesize from human readable string to bytes
  119. *
  120. * @param string $size Size in human readable string like '5MB', '5M', '500B', '50kb' etc.
  121. * @param mixed $default Value to be returned when invalid size was used, for example 'Unknown type'
  122. * @return mixed Number of bytes as integer on success, `$default` on failure if not false
  123. * @throws \Cake\Error\Exception On invalid Unit type.
  124. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::fromReadableSize
  125. */
  126. public static function fromReadableSize($size, $default = false) {
  127. if (ctype_digit($size)) {
  128. return (int)$size;
  129. }
  130. $size = strtoupper($size);
  131. $l = -2;
  132. $i = array_search(substr($size, -2), array('KB', 'MB', 'GB', 'TB', 'PB'));
  133. if ($i === false) {
  134. $l = -1;
  135. $i = array_search(substr($size, -1), array('K', 'M', 'G', 'T', 'P'));
  136. }
  137. if ($i !== false) {
  138. $size = substr($size, 0, $l);
  139. return $size * pow(1024, $i + 1);
  140. }
  141. if (substr($size, -1) === 'B' && ctype_digit(substr($size, 0, -1))) {
  142. $size = substr($size, 0, -1);
  143. return (int)$size;
  144. }
  145. if ($default !== false) {
  146. return $default;
  147. }
  148. throw new Exception('No unit type.');
  149. }
  150. /**
  151. * Formats a number into a percentage string.
  152. *
  153. * Options:
  154. *
  155. * - `multiply`: Multiply the input value by 100 for decimal percentages.
  156. *
  157. * @param float $value A floating point number
  158. * @param int $precision The precision of the returned number
  159. * @param array $options Options
  160. * @return string Percentage string
  161. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage
  162. */
  163. public static function toPercentage($value, $precision = 2, array $options = array()) {
  164. $options += array('multiply' => false);
  165. if ($options['multiply']) {
  166. $value *= 100;
  167. }
  168. return static::precision($value, $precision) . '%';
  169. }
  170. /**
  171. * Formats a number into a currency format.
  172. *
  173. * Options:
  174. *
  175. * - `places` - Number of decimal places to use. ie. 2
  176. * - `before` - The string to place before whole numbers. ie. '['
  177. * - `after` - The string to place after decimal numbers. ie. ']'
  178. * - `thousands` - Thousands separator ie. ','
  179. * - `decimals` - Decimal separator symbol ie. '.'
  180. * - `escape` - Set to false to prevent escaping
  181. *
  182. * @param float $value A floating point number.
  183. * @param array $options An array with options.
  184. * @return string Formatted number
  185. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::format
  186. */
  187. public static function format($value, array $options = []) {
  188. $defaults = array('before' => '', 'after' => '', 'places' => 2,
  189. 'thousands' => ',', 'decimals' => '.', 'escape' => true);
  190. $options += $defaults;
  191. extract($options);
  192. $out = $before . number_format($value, $places, $decimals, $thousands) . $after;
  193. if ($escape) {
  194. return h($out);
  195. }
  196. return $out;
  197. }
  198. /**
  199. * Formats a number into a currency format to show deltas (signed differences in value).
  200. *
  201. * ### Options
  202. *
  203. * - `places` - Number of decimal places to use. ie. 2
  204. * - `fractionExponent` - Fraction exponent of this specific currency. Defaults to 2.
  205. * - `before` - The string to place before whole numbers. ie. '['
  206. * - `after` - The string to place after decimal numbers. ie. ']'
  207. * - `thousands` - Thousands separator ie. ','
  208. * - `decimals` - Decimal separator symbol ie. '.'
  209. *
  210. * @param float $value A floating point number
  211. * @param array $options Options list.
  212. * @return string formatted delta
  213. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::formatDelta
  214. */
  215. public static function formatDelta($value, array $options = array()) {
  216. $places = isset($options['places']) ? $options['places'] : 0;
  217. $value = number_format($value, $places, '.', '');
  218. $sign = $value > 0 ? '+' : '';
  219. $options['before'] = isset($options['before']) ? $options['before'] . $sign : $sign;
  220. return static::format($value, $options);
  221. }
  222. /**
  223. * Alternative number_format() to accommodate multibyte decimals and thousands < PHP 5.4
  224. *
  225. * @param float $value Value to format.
  226. * @param int $places Decimal places to use.
  227. * @param string $decimals Decimal position string.
  228. * @param string $thousands Thousands separator string.
  229. * @return string
  230. */
  231. protected static function _numberFormat($value, $places = 0, $decimals = '.', $thousands = ',') {
  232. if (!isset(self::$_numberFormatSupport)) {
  233. self::$_numberFormatSupport = version_compare(PHP_VERSION, '5.4.0', '>=');
  234. }
  235. if (self::$_numberFormatSupport) {
  236. return number_format($value, $places, $decimals, $thousands);
  237. }
  238. $value = number_format($value, $places, '.', '');
  239. $after = '';
  240. $foundDecimal = strpos($value, '.');
  241. if ($foundDecimal !== false) {
  242. $after = substr($value, $foundDecimal);
  243. $value = substr($value, 0, $foundDecimal);
  244. }
  245. while (($foundThousand = preg_replace('/(\d+)(\d\d\d)/', '\1 \2', $value)) !== $value) {
  246. $value = $foundThousand;
  247. }
  248. $value .= $after;
  249. return strtr($value, array(' ' => $thousands, '.' => $decimals));
  250. }
  251. /**
  252. * Formats a number into a currency format.
  253. *
  254. * ### Options
  255. *
  256. * - `wholeSymbol` - The currency symbol to use for whole numbers,
  257. * greater than 1, or less than -1.
  258. * - `wholePosition` - The position the whole symbol should be placed
  259. * valid options are 'before' & 'after'.
  260. * - `fractionSymbol` - The currency symbol to use for fractional numbers.
  261. * - `fractionPosition` - The position the fraction symbol should be placed
  262. * valid options are 'before' & 'after'.
  263. * - `before` - The currency symbol to place before whole numbers
  264. * ie. '$'. `before` is an alias for `wholeSymbol`.
  265. * - `after` - The currency symbol to place after decimal numbers
  266. * ie. 'c'. Set to boolean false to use no decimal symbol.
  267. * eg. 0.35 => $0.35. `after` is an alias for `fractionSymbol`
  268. * - `zero` - The text to use for zero values, can be a
  269. * string or a number. ie. 0, 'Free!'
  270. * - `places` - Number of decimal places to use. ie. 2
  271. * - `fractionExponent` - Fraction exponent of this specific currency. Defaults to 2.
  272. * - `thousands` - Thousands separator ie. ','
  273. * - `decimals` - Decimal separator symbol ie. '.'
  274. * - `negative` - Symbol for negative numbers. If equal to '()',
  275. * the number will be wrapped with ( and )
  276. * - `escape` - Should the output be escaped for html special characters.
  277. * The default value for this option is controlled by the currency settings.
  278. * By default all currencies contain utf-8 symbols and don't need this changed. If you require
  279. * non HTML encoded symbols you will need to update the settings with the correct bytes.
  280. *
  281. * @param float $value Value to format.
  282. * @param string $currency Shortcut to default options. Valid values are
  283. * 'USD', 'EUR', 'GBP', otherwise set at least 'before' and 'after' options.
  284. * @param array $options Options list.
  285. * @return string Number formatted as a currency.
  286. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::currency
  287. */
  288. public static function currency($value, $currency = null, array $options = array()) {
  289. $default = static::$_currencyDefaults;
  290. if ($currency === null) {
  291. $currency = static::defaultCurrency();
  292. }
  293. if (isset(static::$_currencies[$currency])) {
  294. $default = static::$_currencies[$currency];
  295. } elseif (is_string($currency)) {
  296. $options['before'] = $currency;
  297. }
  298. $options += $default;
  299. if (isset($options['before']) && $options['before'] !== '') {
  300. $options['wholeSymbol'] = $options['before'];
  301. }
  302. if (isset($options['after']) && !$options['after'] !== '') {
  303. $options['fractionSymbol'] = $options['after'];
  304. }
  305. $result = $options['before'] = $options['after'] = null;
  306. $symbolKey = 'whole';
  307. $value = (float)$value;
  308. if (!$value) {
  309. if ($options['zero'] !== 0) {
  310. return $options['zero'];
  311. }
  312. } elseif ($value < 1 && $value > -1) {
  313. if ($options['fractionSymbol'] !== false) {
  314. $multiply = pow(10, $options['fractionExponent']);
  315. $value = $value * $multiply;
  316. $options['places'] = null;
  317. $symbolKey = 'fraction';
  318. }
  319. }
  320. $position = $options[$symbolKey . 'Position'] !== 'after' ? 'before' : 'after';
  321. $options[$position] = $options[$symbolKey . 'Symbol'];
  322. $abs = abs($value);
  323. $result = static::format($abs, $options);
  324. if ($value < 0) {
  325. if ($options['negative'] === '()') {
  326. $result = '(' . $result . ')';
  327. } else {
  328. $result = $options['negative'] . $result;
  329. }
  330. }
  331. return $result;
  332. }
  333. /**
  334. * Add a currency format to the Number helper. Makes reusing
  335. * currency formats easier.
  336. *
  337. * {{{ $number->addFormat('NOK', array('before' => 'Kr. ')); }}}
  338. *
  339. * You can now use `NOK` as a shortform when formatting currency amounts.
  340. *
  341. * {{{ $number->currency($value, 'NOK'); }}}
  342. *
  343. * Added formats are merged with the defaults defined in Cake\Utility\Number::$_currencyDefaults
  344. * See Cake\Utility\Number::currency() for more information on the various options and their function.
  345. *
  346. * @param string $formatName The format name to be used in the future.
  347. * @param array $options The array of options for this format.
  348. * @return void
  349. * @see NumberHelper::currency()
  350. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::addFormat
  351. */
  352. public static function addFormat($formatName, array $options) {
  353. static::$_currencies[$formatName] = $options + static::$_currencyDefaults;
  354. }
  355. /**
  356. * Getter/setter for default currency
  357. *
  358. * @param string $currency Default currency string used by currency() if $currency argument is not provided
  359. * @return string Currency
  360. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::defaultCurrency
  361. */
  362. public static function defaultCurrency($currency = null) {
  363. if ($currency) {
  364. self::$_defaultCurrency = $currency;
  365. }
  366. return self::$_defaultCurrency;
  367. }
  368. }