CNumberFormatter.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 2008-2013 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 percentage 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. * @package system.i18n
  57. * @since 1.0
  58. */
  59. class CNumberFormatter extends CComponent
  60. {
  61. private $_locale;
  62. private $_formats=array();
  63. /**
  64. * Constructor.
  65. * @param mixed $locale locale ID (string) or CLocale instance
  66. */
  67. public function __construct($locale)
  68. {
  69. if(is_string($locale))
  70. $this->_locale=CLocale::getInstance($locale);
  71. else
  72. $this->_locale=$locale;
  73. }
  74. /**
  75. * Formats a number based on the specified pattern.
  76. * Note, if the format contains '%', the number will be multiplied by 100 first.
  77. * If the format contains '‰', the number will be multiplied by 1000.
  78. * If the format contains currency placeholder, it will be replaced by
  79. * the specified localized currency symbol.
  80. * @param string $pattern format pattern
  81. * @param mixed $value the number to be formatted
  82. * @param string $currency 3-letter ISO 4217 code. For example, the code "USD" represents the US Dollar and "EUR" represents the Euro currency.
  83. * The currency placeholder in the pattern will be replaced with the currency symbol.
  84. * If null, no replacement will be done.
  85. * @return string the formatting result.
  86. */
  87. public function format($pattern,$value,$currency=null)
  88. {
  89. $format=$this->parseFormat($pattern);
  90. $result=$this->formatNumber($format,$value);
  91. if($currency===null)
  92. return $result;
  93. elseif(($symbol=$this->_locale->getCurrencySymbol($currency))===null)
  94. $symbol=$currency;
  95. return str_replace('¤',$symbol,$result);
  96. }
  97. /**
  98. * Formats a number using the currency format defined in the locale.
  99. * @param mixed $value the number to be formatted
  100. * @param string $currency 3-letter ISO 4217 code. For example, the code "USD" represents the US Dollar and "EUR" represents the Euro currency.
  101. * The currency placeholder in the pattern will be replaced with the currency symbol.
  102. * @return string the formatting result.
  103. */
  104. public function formatCurrency($value,$currency)
  105. {
  106. return $this->format($this->_locale->getCurrencyFormat(),$value,$currency);
  107. }
  108. /**
  109. * Formats a number using the percentage format defined in the locale.
  110. * Note, if the percentage format contains '%', the number will be multiplied by 100 first.
  111. * If the percentage format contains '‰', the number will be multiplied by 1000.
  112. * @param mixed $value the number to be formatted
  113. * @return string the formatting result.
  114. */
  115. public function formatPercentage($value)
  116. {
  117. return $this->format($this->_locale->getPercentFormat(),$value);
  118. }
  119. /**
  120. * Formats a number using the decimal format defined in the locale.
  121. * @param mixed $value the number to be formatted
  122. * @return string the formatting result.
  123. */
  124. public function formatDecimal($value)
  125. {
  126. return $this->format($this->_locale->getDecimalFormat(),$value);
  127. }
  128. /**
  129. * Formats a number based on a format.
  130. * This is the method that does actual number formatting.
  131. * @param array $format format with the following structure:
  132. * <pre>
  133. * array(
  134. * // number of required digits after the decimal point,
  135. * // will be padded with 0 if not enough digits,
  136. * // -1 means we should drop the decimal point
  137. * 'decimalDigits'=>2,
  138. * // maximum number of digits after the decimal point,
  139. * // additional digits will be truncated.
  140. * 'maxDecimalDigits'=>3,
  141. * // number of required digits before the decimal point,
  142. * // will be padded with 0 if not enough digits
  143. * 'integerDigits'=>1,
  144. * // the primary grouping size, 0 means no grouping
  145. * 'groupSize1'=>3,
  146. * // the secondary grouping size, 0 means no secondary grouping
  147. * 'groupSize2'=>0,
  148. * 'positivePrefix'=>'+', // prefix to positive number
  149. * 'positiveSuffix'=>'', // suffix to positive number
  150. * 'negativePrefix'=>'(', // prefix to negative number
  151. * 'negativeSuffix'=>')', // suffix to negative number
  152. * 'multiplier'=>1, // 100 for percent, 1000 for per mille
  153. * );
  154. * </pre>
  155. * @param mixed $value the number to be formatted
  156. * @return string the formatted result
  157. */
  158. protected function formatNumber($format,$value)
  159. {
  160. $negative=$value<0;
  161. $value=abs($value*$format['multiplier']);
  162. if($format['maxDecimalDigits']>=0)
  163. $value=number_format($value,$format['maxDecimalDigits'],'.','');
  164. $value="$value";
  165. if(false !== $pos=strpos($value,'.'))
  166. {
  167. $integer=substr($value,0,$pos);
  168. $decimal=substr($value,$pos+1);
  169. }
  170. else
  171. {
  172. $integer=$value;
  173. $decimal='';
  174. }
  175. if($format['decimalDigits']>strlen($decimal))
  176. $decimal=str_pad($decimal,$format['decimalDigits'],'0');
  177. elseif($format['decimalDigits']<strlen($decimal))
  178. {
  179. $decimal_temp='';
  180. for($i=strlen($decimal)-1;$i>=0;$i--)
  181. if($decimal[$i]!=='0' || strlen($decimal_temp)>0)
  182. $decimal_temp=$decimal[$i].$decimal_temp;
  183. $decimal=$decimal_temp;
  184. }
  185. if(strlen($decimal)>0)
  186. $decimal=$this->_locale->getNumberSymbol('decimal').$decimal;
  187. $integer=str_pad($integer,$format['integerDigits'],'0',STR_PAD_LEFT);
  188. if($format['groupSize1']>0 && strlen($integer)>$format['groupSize1'])
  189. {
  190. $str1=substr($integer,0,-$format['groupSize1']);
  191. $str2=substr($integer,-$format['groupSize1']);
  192. $size=$format['groupSize2']>0?$format['groupSize2']:$format['groupSize1'];
  193. $str1=str_pad($str1,(int)((strlen($str1)+$size-1)/$size)*$size,' ',STR_PAD_LEFT);
  194. $integer=ltrim(implode($this->_locale->getNumberSymbol('group'),str_split($str1,$size))).$this->_locale->getNumberSymbol('group').$str2;
  195. }
  196. if($negative)
  197. $number=$format['negativePrefix'].$integer.$decimal.$format['negativeSuffix'];
  198. else
  199. $number=$format['positivePrefix'].$integer.$decimal.$format['positiveSuffix'];
  200. return strtr($number,array('%'=>$this->_locale->getNumberSymbol('percentSign'),'‰'=>$this->_locale->getNumberSymbol('perMille')));
  201. }
  202. /**
  203. * Parses a given string pattern.
  204. * @param string $pattern the pattern to be parsed
  205. * @return array the parsed pattern
  206. * @see formatNumber
  207. */
  208. protected function parseFormat($pattern)
  209. {
  210. if(isset($this->_formats[$pattern]))
  211. return $this->_formats[$pattern];
  212. $format=array();
  213. // find out prefix and suffix for positive and negative patterns
  214. $patterns=explode(';',$pattern);
  215. $format['positivePrefix']=$format['positiveSuffix']=$format['negativePrefix']=$format['negativeSuffix']='';
  216. if(preg_match('/^(.*?)[#,\.0]+(.*?)$/',$patterns[0],$matches))
  217. {
  218. $format['positivePrefix']=$matches[1];
  219. $format['positiveSuffix']=$matches[2];
  220. }
  221. if(isset($patterns[1]) && preg_match('/^(.*?)[#,\.0]+(.*?)$/',$patterns[1],$matches)) // with a negative pattern
  222. {
  223. $format['negativePrefix']=$matches[1];
  224. $format['negativeSuffix']=$matches[2];
  225. }
  226. else
  227. {
  228. $format['negativePrefix']=$this->_locale->getNumberSymbol('minusSign').$format['positivePrefix'];
  229. $format['negativeSuffix']=$format['positiveSuffix'];
  230. }
  231. $pat=$patterns[0];
  232. // find out multiplier
  233. if(strpos($pat,'%')!==false)
  234. $format['multiplier']=100;
  235. elseif(strpos($pat,'‰')!==false)
  236. $format['multiplier']=1000;
  237. else
  238. $format['multiplier']=1;
  239. // find out things about decimal part
  240. if(($pos=strpos($pat,'.'))!==false)
  241. {
  242. if(($pos2=strrpos($pat,'0'))>$pos)
  243. $format['decimalDigits']=$pos2-$pos;
  244. else
  245. $format['decimalDigits']=0;
  246. if(($pos3=strrpos($pat,'#'))>=$pos2)
  247. $format['maxDecimalDigits']=$pos3-$pos;
  248. else
  249. $format['maxDecimalDigits']=$format['decimalDigits'];
  250. $pat=substr($pat,0,$pos);
  251. }
  252. else // no decimal part
  253. {
  254. $format['decimalDigits']=0;
  255. $format['maxDecimalDigits']=0;
  256. }
  257. // find out things about integer part
  258. $p=str_replace(',','',$pat);
  259. if(($pos=strpos($p,'0'))!==false)
  260. $format['integerDigits']=strrpos($p,'0')-$pos+1;
  261. else
  262. $format['integerDigits']=0;
  263. // find out group sizes. some patterns may have two different group sizes
  264. $p=str_replace('#','0',$pat);
  265. if(($pos=strrpos($pat,','))!==false)
  266. {
  267. $format['groupSize1']=strrpos($p,'0')-$pos;
  268. if(($pos2=strrpos(substr($p,0,$pos),','))!==false)
  269. $format['groupSize2']=$pos-$pos2-1;
  270. else
  271. $format['groupSize2']=0;
  272. }
  273. else
  274. $format['groupSize1']=$format['groupSize2']=0;
  275. return $this->_formats[$pattern]=$format;
  276. }
  277. }