1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
<?php
/*
* This file is part of the ICanBoogie package.
*
* (c) Olivier Laviale <olivier.laviale@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Original code: http://code.google.com/p/yii/source/browse/tags/1.1.6/framework/i18n/CNumberFormatter.php
*/
namespace ICanBoogie\I18n;
/**
* NumberFormatter provides number localization features.
*
* NumberFormatter formats a number (integer or float) and outputs a string
* based on the specified format. A NumberFormatter instance is associated with a locale,
* and thus generates the string representation of the number in a locale-dependent fashion.
*
* NumberFormatter currently supports currency format, percentage format, decimal format,
* and custom format. The first three formats are specified in the locale data, while the custom
* format allows you to enter an arbitrary format string.
*
* A format string may consist of the following special characters:
* <ul>
* <li>dot (.): the decimal point. It will be replaced with the localized decimal point.</li>
* <li>comma (,): the grouping separator. It will be replaced with the localized grouping separator.</li>
* <li>zero (0): required digit. This specifies the places where a digit must appear (will pad 0 if not).</li>
* <li>hash (#): optional digit. This is mainly used to specify the location of decimal point and grouping separators.</li>
* <li>currency (¤): the currency placeholder. It will be replaced with the localized currency symbol.</li>
* <li>percentage (%): the percetage mark. If appearing, the number will be multiplied by 100 before being formatted.</li>
* <li>permillage (‰): the permillage mark. If appearing, the number will be multiplied by 1000 before being formatted.</li>
* <li>semicolon (;): the character separating positive and negative number sub-patterns.</li>
* </ul>
*
* Anything surrounding the pattern (or sub-patterns) will be kept.
*
* The followings are some examples:
* <pre>
* Pattern "#,##0.00" will format 12345.678 as "12,345.68".
* Pattern "#,#,#0.00" will format 12345.6 as "1,2,3,45.60".
* </pre>
* Note, in the first example, the number is rounded first before applying the formatting.
* And in the second example, the pattern specifies two grouping sizes.
*
* NumberFormatter attempts to implement number formatting according to
* the {@link http://www.unicode.org/reports/tr35/ Unicode Technical Standard #35}.
* The following features are NOT implemented:
* <ul>
* <li>significant digit</li>
* <li>scientific format</li>
* <li>arbitrary literal characters</li>
* <li>arbitrary padding</li>
* </ul>
*
* @author Wei Zhuo <weizhuo[at]gmail[dot]com>
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Olivier Laviale <gmail@olvlvl.com>
*/
class NumberFormatter
{
/**
* Locale.
*
* @var Locale
*/
protected $locale;
/**
* Shortcut to the locale `numbers` convention.
*
* @var array
*/
protected $conventions;
/**
* Parsed formats cache.
*
* @var array
*/
private $formats = array();
/**
* Constructor.
*
* @param Locale $locale Locale instance.
*/
public function __construct(Locale $locale)
{
$this->locale = $locale;
$this->conventions = $locale['numbers'];
}
/**
* Formats a number based on the specified pattern.
* Note, if the format contains '%', the number will be multiplied by 100 first.
* If the format contains '‰', the number will be multiplied by 1000.
* If the format contains currency placeholder, it will be replaced by
* the specified localized currency symbol.
* @param string $pattern format pattern
* @param mixed $value the number to be formatted
* @param string $currency 3-letter ISO 4217 code. For example, the code "USD" represents the US Dollar and "EUR" represents the Euro currency.
* The currency placeholder in the pattern will be replaced with the currency symbol.
* If null, no replacement will be done.
* @return string the formatting result.
*/
public function format($value, $pattern=null, $currency=null)
{
if (!$pattern)
{
$pattern = $this->conventions['decimalFormats']['decimalFormatLength']['decimalFormat']['pattern'];
}
$format = $this->parse_format($pattern);
$result = $this->format_number($value, $format);
if ($currency === null)
{
return $result;
}
$currencies = $this->conventions['currencies'];
$symbol = isset($currencies[$currency]['symbol']) ? $currencies[$currency]['symbol'] : $currency;
return str_replace('¤', $symbol, $result);
}
/**
* Formats a number using the currency format defined in the locale.
* @param mixed $value the number to be formatted
* @param string $currency 3-letter ISO 4217 code. For example, the code "USD" represents the US Dollar and "EUR" represents the Euro currency.
* The currency placeholder in the pattern will be replaced with the currency symbol.
* @return string the formatting result.
*/
public function format_currency($value, $currency)
{
return $this->format($value, $this->conventions['currencyFormats']['currencyFormatLength']['currencyFormat']['pattern'], $currency);
}
/**
* Formats a number using the percentage format defined in the locale.
* Note, if the percentage format contains '%', the number will be multiplied by 100 first.
* If the percentage format contains '‰', the number will be multiplied by 1000.
* @param mixed $value the number to be formatted
* @return string the formatting result.
*/
public function format_percentage($value)
{
return $this->format($this->locale->getPercentFormat(), $value);
}
/**
* Formats a number using the decimal format defined in the locale.
* @param mixed $value the number to be formatted
* @return string the formatting result.
*/
public function format_decimal($value)
{
return $this->format($this->locale->getDecimalFormat(),$value);
}
/**
* Formats a number based on a format.
* This is the method that does actual number formatting.
* @param array $format format with the following structure:
* <pre>
* array(
* 'decimalDigits'=>2, // number of required digits after decimal point; 0s will be padded if not enough digits; if -1, it means we should drop decimal point
* 'maxDecimalDigits'=>3, // maximum number of digits after decimal point. Additional digits will be truncated.
* 'integerDigits'=>1, // number of required digits before decimal point; 0s will be padded if not enough digits
* 'groupSize1'=>3, // the primary grouping size; if 0, it means no grouping
* 'groupSize2'=>0, // the secondary grouping size; if 0, it means no secondary grouping
* 'positivePrefix'=>'+', // prefix to positive number
* 'positiveSuffix'=>'', // suffix to positive number
* 'negativePrefix'=>'(', // prefix to negative number
* 'negativeSuffix'=>')', // suffix to negative number
* 'multiplier'=>1, // 100 for percent, 1000 for per mille
* );
* </pre>
* @param mixed $value the number to be formatted
* @return string the formatted result
*/
protected function format_number($value, $format)
{
$negative=$value<0;
$value=abs($value*$format['multiplier']);
if($format['maxDecimalDigits']>=0)
$value=round($value,$format['maxDecimalDigits']);
$value="$value";
if(($pos=strpos($value,'.'))!==false)
{
$integer=substr($value,0,$pos);
$decimal=substr($value,$pos+1);
}
else
{
$integer=$value;
$decimal='';
}
if($format['decimalDigits']>strlen($decimal))
$decimal=str_pad($decimal,$format['decimalDigits'],'0');
if (strlen($decimal))
{
$decimal = $this->conventions['symbols']['decimal'] . $decimal;
}
$integer=str_pad($integer,$format['integerDigits'],'0',STR_PAD_LEFT);
if($format['groupSize1']>0 && strlen($integer)>$format['groupSize1'])
{
$str1=substr($integer,0,-$format['groupSize1']);
$str2=substr($integer,-$format['groupSize1']);
$size=$format['groupSize2']>0?$format['groupSize2']:$format['groupSize1'];
$str1=str_pad($str1,(int)((strlen($str1)+$size-1)/$size)*$size,' ',STR_PAD_LEFT);
$integer=ltrim(implode($this->conventions['symbols']['group'],str_split($str1,$size))).$this->conventions['symbols']['group'].$str2;
}
if($negative)
$number=$format['negativePrefix'].$integer.$decimal.$format['negativeSuffix'];
else
$number=$format['positivePrefix'].$integer.$decimal.$format['positiveSuffix'];
return strtr($number,array('%'=>$this->conventions['symbols']['percentSign'],'‰'=>$this->conventions['symbols']['perMille']));
}
/**
* Parses a given string pattern.
*
* @param string $pattern the pattern to be parsed
*
* @return array the parsed pattern
*
* @see format_number
*/
protected function parse_format($pattern)
{
if (isset($this->formats[$pattern]))
{
return $this->formats[$pattern];
}
$format = array
(
'positivePrefix' => '',
'positiveSuffix' => '',
'negativePrefix' => '',
'negativeSuffix' => ''
);
// find out prefix and suffix for positive and negative patterns
$patterns = explode(';',$pattern);
if (preg_match('/^(.*?)[#,\.0]+(.*?)$/', $patterns[0], $matches))
{
$format['positivePrefix'] = $matches[1];
$format['positiveSuffix'] = $matches[2];
}
if (isset($patterns[1]) && preg_match('/^(.*?)[#,\.0]+(.*?)$/', $patterns[1], $matches)) // with a negative pattern
{
$format['negativePrefix'] = $matches[1];
$format['negativeSuffix'] = $matches[2];
}
else
{
$format['negativePrefix'] = $this->conventions['symbols']['minusSign'] . $format['positivePrefix'];
$format['negativeSuffix'] = $format['positiveSuffix'];
}
$pat = $patterns[0];
// find out multiplier
if (strpos($pat,'%') !== false)
{
$format['multiplier'] = 100;
}
else if (strpos($pat,'‰') !== false)
{
$format['multiplier'] = 1000;
}
else
{
$format['multiplier'] = 1;
}
// find out things about decimal part
if (($pos = strpos($pat,'.')) !== false)
{
if (($pos2 = strrpos($pat,'0')) > $pos)
{
$format['decimalDigits'] = $pos2-$pos;
}
else
{
$format['decimalDigits'] = 0;
}
if (($pos3 = strrpos($pat,'#')) >= $pos2)
{
$format['maxDecimalDigits'] = $pos3 - $pos;
}
else
{
$format['maxDecimalDigits'] = $format['decimalDigits'];
}
$pat = substr($pat, 0, $pos);
}
else // no decimal part
{
$format['decimalDigits'] = 0;
$format['maxDecimalDigits'] = 0;
}
// find out things about integer part
$p = str_replace(',','',$pat);
if (($pos=strpos($p,'0')) !== false)
{
$format['integerDigits'] = strrpos($p, '0') - $pos + 1;
}
else
{
$format['integerDigits'] = 0;
}
// find out group sizes. some patterns may have two different group sizes
$p = str_replace('#', '0', $pat);
if (($pos = strrpos($pat, ',')) !== false)
{
$format['groupSize1'] = strrpos($p, '0') - $pos;
if (($pos2 = strrpos(substr($p, 0, $pos), ',')) !== false)
{
$format['groupSize2'] = $pos - $pos2 - 1;
}
else
{
$format['groupSize2'] = 0;
}
}
else
{
$format['groupSize1'] = $format['groupSize2'] = 0;
}
return $this->formats[$pattern] = $format;
}
}