1: <?php
2: /**
3: * CakeNumber Utility.
4: *
5: * Methods to make numbers more readable.
6: *
7: * PHP 5
8: *
9: * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
10: * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
11: *
12: * Licensed under The MIT License
13: * Redistributions of files must retain the above copyright notice.
14: *
15: * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
16: * @link http://cakephp.org CakePHP(tm) Project
17: * @package Cake.Utility
18: * @since CakePHP(tm) v 0.10.0.1076
19: * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
20: */
21:
22: /**
23: * Number helper library.
24: *
25: * Methods to make numbers more readable.
26: *
27: * @package Cake.Utility
28: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html
29: */
30: class CakeNumber {
31:
32: /**
33: * Currencies supported by the helper. You can add additional currency formats
34: * with CakeNumber::addFormat
35: *
36: * @var array
37: */
38: protected static $_currencies = array(
39: 'USD' => array(
40: 'wholeSymbol' => '$', 'wholePosition' => 'before', 'fractionSymbol' => 'c', 'fractionPosition' => 'after',
41: 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true
42: ),
43: 'GBP' => array(
44: 'wholeSymbol' => '£', 'wholePosition' => 'before', 'fractionSymbol' => 'p', 'fractionPosition' => 'after',
45: 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()','escape' => false
46: ),
47: 'EUR' => array(
48: 'wholeSymbol' => '€', 'wholePosition' => 'before', 'fractionSymbol' => false, 'fractionPosition' => 'after',
49: 'zero' => 0, 'places' => 2, 'thousands' => '.', 'decimals' => ',', 'negative' => '()', 'escape' => false
50: )
51: );
52:
53: /**
54: * Default options for currency formats
55: *
56: * @var array
57: */
58: protected static $_currencyDefaults = array(
59: 'wholeSymbol' => '', 'wholePosition' => 'before', 'fractionSymbol' => '', 'fractionPosition' => 'after',
60: 'zero' => '0', 'places' => 2, 'thousands' => ',', 'decimals' => '.','negative' => '()', 'escape' => true,
61: );
62:
63: /**
64: * If native number_format() should be used. If >= PHP5.4
65: *
66: * @var boolean
67: */
68: protected static $_numberFormatSupport = null;
69:
70: /**
71: * Formats a number with a level of precision.
72: *
73: * @param float $number A floating point number.
74: * @param integer $precision The precision of the returned number.
75: * @return float Formatted float.
76: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::precision
77: */
78: public static function precision($number, $precision = 3) {
79: return sprintf("%01.{$precision}F", $number);
80: }
81:
82: /**
83: * Returns a formatted-for-humans file size.
84: *
85: * @param integer $size Size in bytes
86: * @return string Human readable size
87: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize
88: */
89: public static function toReadableSize($size) {
90: switch (true) {
91: case $size < 1024:
92: return __dn('cake', '%d Byte', '%d Bytes', $size, $size);
93: case round($size / 1024) < 1024:
94: return __d('cake', '%d KB', self::precision($size / 1024, 0));
95: case round($size / 1024 / 1024, 2) < 1024:
96: return __d('cake', '%.2f MB', self::precision($size / 1024 / 1024, 2));
97: case round($size / 1024 / 1024 / 1024, 2) < 1024:
98: return __d('cake', '%.2f GB', self::precision($size / 1024 / 1024 / 1024, 2));
99: default:
100: return __d('cake', '%.2f TB', self::precision($size / 1024 / 1024 / 1024 / 1024, 2));
101: }
102: }
103:
104: /**
105: * Formats a number into a percentage string.
106: *
107: * @param float $number A floating point number
108: * @param integer $precision The precision of the returned number
109: * @return string Percentage string
110: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage
111: */
112: public static function toPercentage($number, $precision = 2) {
113: return self::precision($number, $precision) . '%';
114: }
115:
116: /**
117: * Formats a number into a currency format.
118: *
119: * @param float $number A floating point number
120: * @param integer $options if int then places, if string then before, if (,.-) then use it
121: * or array with places and before keys
122: * @return string formatted number
123: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::format
124: */
125: public static function format($number, $options = false) {
126: $places = 0;
127: if (is_int($options)) {
128: $places = $options;
129: }
130:
131: $separators = array(',', '.', '-', ':');
132:
133: $before = $after = null;
134: if (is_string($options) && !in_array($options, $separators)) {
135: $before = $options;
136: }
137: $thousands = ',';
138: if (!is_array($options) && in_array($options, $separators)) {
139: $thousands = $options;
140: }
141: $decimals = '.';
142: if (!is_array($options) && in_array($options, $separators)) {
143: $decimals = $options;
144: }
145:
146: $escape = true;
147: if (is_array($options)) {
148: $options = array_merge(array('before' => '$', 'places' => 2, 'thousands' => ',', 'decimals' => '.'), $options);
149: extract($options);
150: }
151:
152: $out = $before . self::_numberFormat($number, $places, $decimals, $thousands) . $after;
153:
154: if ($escape) {
155: return h($out);
156: }
157: return $out;
158: }
159:
160: /**
161: * Alternative number_format() to accommodate multibyte decimals and thousands < PHP 5.4
162: *
163: * @param float $number
164: * @param integer $places
165: * @param string $decimals
166: * @param string $thousands
167: * @return string
168: */
169: protected static function _numberFormat($number, $places = 0, $decimals = '.', $thousands = ',') {
170: if (!isset(self::$_numberFormatSupport)) {
171: self::$_numberFormatSupport = version_compare(PHP_VERSION, '5.4.0', '>=');
172: }
173: if (self::$_numberFormatSupport) {
174: return number_format($number, $places, $decimals, $thousands);
175: }
176: $number = number_format($number, $places, '.', '');
177: $after = '';
178: $foundDecimal = strpos($number, '.');
179: if ($foundDecimal !== false) {
180: $after = substr($number, $foundDecimal);
181: $number = substr($number, 0, $foundDecimal);
182: }
183: while (($foundThousand = preg_replace('/(\d+)(\d\d\d)/', '\1 \2', $number)) != $number) {
184: $number = $foundThousand;
185: }
186: $number .= $after;
187: return strtr($number, array(' ' => $thousands, '.' => $decimals));
188: }
189:
190: /**
191: * Formats a number into a currency format.
192: *
193: * ### Options
194: *
195: * - `wholeSymbol` - The currency symbol to use for whole numbers,
196: * greater than 1, or less than -1.
197: * - `wholePosition` - The position the whole symbol should be placed
198: * valid options are 'before' & 'after'.
199: * - `fractionSymbol` - The currency symbol to use for fractional numbers.
200: * - `fractionPosition` - The position the fraction symbol should be placed
201: * valid options are 'before' & 'after'.
202: * - `before` - The currency symbol to place before whole numbers
203: * ie. '$'. `before` is an alias for `wholeSymbol`.
204: * - `after` - The currency symbol to place after decimal numbers
205: * ie. 'c'. Set to boolean false to use no decimal symbol.
206: * eg. 0.35 => $0.35. `after` is an alias for `fractionSymbol`
207: * - `zero` - The text to use for zero values, can be a
208: * string or a number. ie. 0, 'Free!'
209: * - `places` - Number of decimal places to use. ie. 2
210: * - `thousands` - Thousands separator ie. ','
211: * - `decimals` - Decimal separator symbol ie. '.'
212: * - `negative` - Symbol for negative numbers. If equal to '()',
213: * the number will be wrapped with ( and )
214: * - `escape` - Should the output be escaped for html special characters.
215: * The default value for this option is controlled by the currency settings.
216: * By default the EUR, and GBP contain HTML encoded symbols. If you require non HTML
217: * encoded symbols you will need to update the settings with the correct bytes.
218: *
219: * @param float $number
220: * @param string $currency Shortcut to default options. Valid values are
221: * 'USD', 'EUR', 'GBP', otherwise set at least 'before' and 'after' options.
222: * @param array $options
223: * @return string Number formatted as a currency.
224: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::currency
225: */
226: public static function currency($number, $currency = 'USD', $options = array()) {
227: $default = self::$_currencyDefaults;
228:
229: if (isset(self::$_currencies[$currency])) {
230: $default = self::$_currencies[$currency];
231: } elseif (is_string($currency)) {
232: $options['before'] = $currency;
233: }
234:
235: $options = array_merge($default, $options);
236:
237: if (isset($options['before']) && $options['before'] !== '') {
238: $options['wholeSymbol'] = $options['before'];
239: }
240: if (isset($options['after']) && !$options['after'] !== '') {
241: $options['fractionSymbol'] = $options['after'];
242: }
243:
244: $result = $options['before'] = $options['after'] = null;
245:
246: $symbolKey = 'whole';
247: if ($number == 0 ) {
248: if ($options['zero'] !== 0 ) {
249: return $options['zero'];
250: }
251: } elseif ($number < 1 && $number > -1 ) {
252: if ($options['fractionSymbol'] !== false) {
253: $multiply = intval('1' . str_pad('', $options['places'], '0'));
254: $number = $number * $multiply;
255: $options['places'] = null;
256: $symbolKey = 'fraction';
257: }
258: }
259:
260: $position = $options[$symbolKey . 'Position'] != 'after' ? 'before' : 'after';
261: $options[$position] = $options[$symbolKey . 'Symbol'];
262:
263: $abs = abs($number);
264: $result = self::format($abs, $options);
265:
266: if ($number < 0 ) {
267: if ($options['negative'] == '()') {
268: $result = '(' . $result . ')';
269: } else {
270: $result = $options['negative'] . $result;
271: }
272: }
273: return $result;
274: }
275:
276: /**
277: * Add a currency format to the Number helper. Makes reusing
278: * currency formats easier.
279: *
280: * {{{ $number->addFormat('NOK', array('before' => 'Kr. ')); }}}
281: *
282: * You can now use `NOK` as a shortform when formatting currency amounts.
283: *
284: * {{{ $number->currency($value, 'NOK'); }}}
285: *
286: * Added formats are merged with the defaults defined in CakeNumber::$_currencyDefaults
287: * See CakeNumber::currency() for more information on the various options and their function.
288: *
289: * @param string $formatName The format name to be used in the future.
290: * @param array $options The array of options for this format.
291: * @return void
292: * @see NumberHelper::currency()
293: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::addFormat
294: */
295: public static function addFormat($formatName, $options) {
296: self::$_currencies[$formatName] = $options + self::$_currencyDefaults;
297: }
298:
299: }
300: