PageRenderTime 47ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/i18n/CNumberFormatter.php

https://bitbucket.org/dinhtrung/yiicorecms/
PHP | 280 lines | 135 code | 19 blank | 126 comment | 25 complexity | 22fdf2778c75731c140c9c781f163470 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, CC0-1.0, BSD-2-Clause, GPL-2.0, LGPL-2.1, LGPL-3.0
  1. <?php
  2. /**
  3. * CNumberFormatter class file.
  4. *
  5. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  6. * @author Qiang Xue <qiang.xue@gmail.com>
  7. * @link http://www.yiiframework.com/
  8. * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  9. * @license http://www.yiiframework.com/license/
  10. */
  11. /**
  12. * CNumberFormatter provides number localization functionalities.
  13. *
  14. * CNumberFormatter formats a number (integer or float) and outputs a string
  15. * based on the specified format. A CNumberFormatter instance is associated with a locale,
  16. * and thus generates the string representation of the number in a locale-dependent fashion.
  17. *
  18. * CNumberFormatter currently supports currency format, percentage format, decimal format,
  19. * and custom format. The first three formats are specified in the locale data, while the custom
  20. * format allows you to enter an arbitrary format string.
  21. *
  22. * A format string may consist of the following special characters:
  23. * <ul>
  24. * <li>dot (.): the decimal point. It will be replaced with the localized decimal point.</li>
  25. * <li>comma (,): the grouping separator. It will be replaced with the localized grouping separator.</li>
  26. * <li>zero (0): required digit. This specifies the places where a digit must appear (will pad 0 if not).</li>
  27. * <li>hash (#): optional digit. This is mainly used to specify the location of decimal point and grouping separators.</li>
  28. * <li>currency (¤): the currency placeholder. It will be replaced with the localized currency symbol.</li>
  29. * <li>percentage (%): the percetage mark. If appearing, the number will be multiplied by 100 before being formatted.</li>
  30. * <li>permillage (‰): the permillage mark. If appearing, the number will be multiplied by 1000 before being formatted.</li>
  31. * <li>semicolon (;): the character separating positive and negative number sub-patterns.</li>
  32. * </ul>
  33. *
  34. * Anything surrounding the pattern (or sub-patterns) will be kept.
  35. *
  36. * The followings are some examples:
  37. * <pre>
  38. * Pattern "#,##0.00" will format 12345.678 as "12,345.68".
  39. * Pattern "#,#,#0.00" will format 12345.6 as "1,2,3,45.60".
  40. * </pre>
  41. * Note, in the first example, the number is rounded first before applying the formatting.
  42. * And in the second example, the pattern specifies two grouping sizes.
  43. *
  44. * CNumberFormatter attempts to implement number formatting according to
  45. * the {@link http://www.unicode.org/reports/tr35/ Unicode Technical Standard #35}.
  46. * The following features are NOT implemented:
  47. * <ul>
  48. * <li>significant digit</li>
  49. * <li>scientific format</li>
  50. * <li>arbitrary literal characters</li>
  51. * <li>arbitrary padding</li>
  52. * </ul>
  53. *
  54. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  55. * @author Qiang Xue <qiang.xue@gmail.com>
  56. * @version $Id: CNumberFormatter.php 2798 2011-01-01 19:29:03Z qiang.xue $
  57. * @package system.i18n
  58. * @since 1.0
  59. */
  60. class CNumberFormatter extends CComponent
  61. {
  62. private $_locale;
  63. private $_formats=array();
  64. /**
  65. * Constructor.
  66. * @param mixed $locale locale ID (string) or CLocale instance
  67. */
  68. public function __construct($locale)
  69. {
  70. if(is_string($locale))
  71. $this->_locale=CLocale::getInstance($locale);
  72. else
  73. $this->_locale=$locale;
  74. }
  75. /**
  76. * Formats a number based on the specified pattern.
  77. * Note, if the format contains '%', the number will be multiplied by 100 first.
  78. * If the format contains '‰', the number will be multiplied by 1000.
  79. * If the format contains currency placeholder, it will be replaced by
  80. * the specified localized currency symbol.
  81. * @param string $pattern format pattern
  82. * @param mixed $value the number to be formatted
  83. * @param string $currency 3-letter ISO 4217 code. For example, the code "USD" represents the US Dollar and "EUR" represents the Euro currency.
  84. * The currency placeholder in the pattern will be replaced with the currency symbol.
  85. * If null, no replacement will be done.
  86. * @return string the formatting result.
  87. */
  88. public function format($pattern,$value,$currency=null)
  89. {
  90. $format=$this->parseFormat($pattern);
  91. $result=$this->formatNumber($format,$value);
  92. if($currency===null)
  93. return $result;
  94. else if(($symbol=$this->_locale->getCurrencySymbol($currency))===null)
  95. $symbol=$currency;
  96. return str_replace('¤',$symbol,$result);
  97. }
  98. /**
  99. * Formats a number using the currency format defined in the locale.
  100. * @param mixed $value the number to be formatted
  101. * @param string $currency 3-letter ISO 4217 code. For example, the code "USD" represents the US Dollar and "EUR" represents the Euro currency.
  102. * The currency placeholder in the pattern will be replaced with the currency symbol.
  103. * @return string the formatting result.
  104. */
  105. public function formatCurrency($value,$currency)
  106. {
  107. return $this->format($this->_locale->getCurrencyFormat(),$value,$currency);
  108. }
  109. /**
  110. * Formats a number using the percentage format defined in the locale.
  111. * Note, if the percentage format contains '%', the number will be multiplied by 100 first.
  112. * If the percentage format contains '‰', the number will be multiplied by 1000.
  113. * @param mixed $value the number to be formatted
  114. * @return string the formatting result.
  115. */
  116. public function formatPercentage($value)
  117. {
  118. return $this->format($this->_locale->getPercentFormat(),$value);
  119. }
  120. /**
  121. * Formats a number using the decimal format defined in the locale.
  122. * @param mixed $value the number to be formatted
  123. * @return string the formatting result.
  124. */
  125. public function formatDecimal($value)
  126. {
  127. return $this->format($this->_locale->getDecimalFormat(),$value);
  128. }
  129. /**
  130. * Formats a number based on a format.
  131. * This is the method that does actual number formatting.
  132. * @param array $format format with the following structure:
  133. * <pre>
  134. * array(
  135. * '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
  136. * 'maxDecimalDigits'=>3, // maximum number of digits after decimal point. Additional digits will be truncated.
  137. * 'integerDigits'=>1, // number of required digits before decimal point; 0s will be padded if not enough digits
  138. * 'groupSize1'=>3, // the primary grouping size; if 0, it means no grouping
  139. * 'groupSize2'=>0, // the secondary grouping size; if 0, it means no secondary grouping
  140. * 'positivePrefix'=>'+', // prefix to positive number
  141. * 'positiveSuffix'=>'', // suffix to positive number
  142. * 'negativePrefix'=>'(', // prefix to negative number
  143. * 'negativeSuffix'=>')', // suffix to negative number
  144. * 'multiplier'=>1, // 100 for percent, 1000 for per mille
  145. * );
  146. * </pre>
  147. * @param mixed $value the number to be formatted
  148. * @return string the formatted result
  149. */
  150. protected function formatNumber($format,$value)
  151. {
  152. $negative=$value<0;
  153. $value=abs($value*$format['multiplier']);
  154. if($format['maxDecimalDigits']>=0)
  155. $value=round($value,$format['maxDecimalDigits']);
  156. $value="$value";
  157. if(($pos=strpos($value,'.'))!==false)
  158. {
  159. $integer=substr($value,0,$pos);
  160. $decimal=substr($value,$pos+1);
  161. }
  162. else
  163. {
  164. $integer=$value;
  165. $decimal='';
  166. }
  167. if($format['decimalDigits']>strlen($decimal))
  168. $decimal=str_pad($decimal,$format['decimalDigits'],'0');
  169. if(strlen($decimal)>0)
  170. $decimal=$this->_locale->getNumberSymbol('decimal').$decimal;
  171. $integer=str_pad($integer,$format['integerDigits'],'0',STR_PAD_LEFT);
  172. if($format['groupSize1']>0 && strlen($integer)>$format['groupSize1'])
  173. {
  174. $str1=substr($integer,0,-$format['groupSize1']);
  175. $str2=substr($integer,-$format['groupSize1']);
  176. $size=$format['groupSize2']>0?$format['groupSize2']:$format['groupSize1'];
  177. $str1=str_pad($str1,(int)((strlen($str1)+$size-1)/$size)*$size,' ',STR_PAD_LEFT);
  178. $integer=ltrim(implode($this->_locale->getNumberSymbol('group'),str_split($str1,$size))).$this->_locale->getNumberSymbol('group').$str2;
  179. }
  180. if($negative)
  181. $number=$format['negativePrefix'].$integer.$decimal.$format['negativeSuffix'];
  182. else
  183. $number=$format['positivePrefix'].$integer.$decimal.$format['positiveSuffix'];
  184. return strtr($number,array('%'=>$this->_locale->getNumberSymbol('percentSign'),'‰'=>$this->_locale->getNumberSymbol('perMille')));
  185. }
  186. /**
  187. * Parses a given string pattern.
  188. * @param string $pattern the pattern to be parsed
  189. * @return array the parsed pattern
  190. * @see formatNumber
  191. */
  192. protected function parseFormat($pattern)
  193. {
  194. if(isset($this->_formats[$pattern]))
  195. return $this->_formats[$pattern];
  196. $format=array();
  197. // find out prefix and suffix for positive and negative patterns
  198. $patterns=explode(';',$pattern);
  199. $format['positivePrefix']=$format['positiveSuffix']=$format['negativePrefix']=$format['negativeSuffix']='';
  200. if(preg_match('/^(.*?)[#,\.0]+(.*?)$/',$patterns[0],$matches))
  201. {
  202. $format['positivePrefix']=$matches[1];
  203. $format['positiveSuffix']=$matches[2];
  204. }
  205. if(isset($patterns[1]) && preg_match('/^(.*?)[#,\.0]+(.*?)$/',$patterns[1],$matches)) // with a negative pattern
  206. {
  207. $format['negativePrefix']=$matches[1];
  208. $format['negativeSuffix']=$matches[2];
  209. }
  210. else
  211. {
  212. $format['negativePrefix']=$this->_locale->getNumberSymbol('minusSign').$format['positivePrefix'];
  213. $format['negativeSuffix']=$format['positiveSuffix'];
  214. }
  215. $pat=$patterns[0];
  216. // find out multiplier
  217. if(strpos($pat,'%')!==false)
  218. $format['multiplier']=100;
  219. else if(strpos($pat,'‰')!==false)
  220. $format['multiplier']=1000;
  221. else
  222. $format['multiplier']=1;
  223. // find out things about decimal part
  224. if(($pos=strpos($pat,'.'))!==false)
  225. {
  226. if(($pos2=strrpos($pat,'0'))>$pos)
  227. $format['decimalDigits']=$pos2-$pos;
  228. else
  229. $format['decimalDigits']=0;
  230. if(($pos3=strrpos($pat,'#'))>=$pos2)
  231. $format['maxDecimalDigits']=$pos3-$pos;
  232. else
  233. $format['maxDecimalDigits']=$format['decimalDigits'];
  234. $pat=substr($pat,0,$pos);
  235. }
  236. else // no decimal part
  237. {
  238. $format['decimalDigits']=0;
  239. $format['maxDecimalDigits']=0;
  240. }
  241. // find out things about integer part
  242. $p=str_replace(',','',$pat);
  243. if(($pos=strpos($p,'0'))!==false)
  244. $format['integerDigits']=strrpos($p,'0')-$pos+1;
  245. else
  246. $format['integerDigits']=0;
  247. // find out group sizes. some patterns may have two different group sizes
  248. $p=str_replace('#','0',$pat);
  249. if(($pos=strrpos($pat,','))!==false)
  250. {
  251. $format['groupSize1']=strrpos($p,'0')-$pos;
  252. if(($pos2=strrpos(substr($p,0,$pos),','))!==false)
  253. $format['groupSize2']=$pos-$pos2-1;
  254. else
  255. $format['groupSize2']=0;
  256. }
  257. else
  258. $format['groupSize1']=$format['groupSize2']=0;
  259. return $this->_formats[$pattern]=$format;
  260. }
  261. }