PageRenderTime 37ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/protected/extensions/PHPExcel/vendor/PHPExcel/Style/NumberFormat.php

https://bitbucket.org/y_widyatama/ijepa2
PHP | 711 lines | 418 code | 80 blank | 213 comment | 61 complexity | cf5f4ea44b176e781c9b73001e5cf527 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause
  1. <?php
  2. /**
  3. * PHPExcel
  4. *
  5. * Copyright (c) 2006 - 2014 PHPExcel
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * @category PHPExcel
  22. * @package PHPExcel_Style
  23. * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
  24. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  25. * @version ##VERSION##, ##DATE##
  26. */
  27. /**
  28. * PHPExcel_Style_NumberFormat
  29. *
  30. * @category PHPExcel
  31. * @package PHPExcel_Style
  32. * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
  33. */
  34. class PHPExcel_Style_NumberFormat extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable
  35. {
  36. /* Pre-defined formats */
  37. const FORMAT_GENERAL = 'General';
  38. const FORMAT_TEXT = '@';
  39. const FORMAT_NUMBER = '0';
  40. const FORMAT_NUMBER_00 = '0.00';
  41. const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00';
  42. const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-';
  43. const FORMAT_PERCENTAGE = '0%';
  44. const FORMAT_PERCENTAGE_00 = '0.00%';
  45. const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd';
  46. const FORMAT_DATE_YYYYMMDD = 'yy-mm-dd';
  47. const FORMAT_DATE_DDMMYYYY = 'dd/mm/yy';
  48. const FORMAT_DATE_DMYSLASH = 'd/m/y';
  49. const FORMAT_DATE_DMYMINUS = 'd-m-y';
  50. const FORMAT_DATE_DMMINUS = 'd-m';
  51. const FORMAT_DATE_MYMINUS = 'm-y';
  52. const FORMAT_DATE_XLSX14 = 'mm-dd-yy';
  53. const FORMAT_DATE_XLSX15 = 'd-mmm-yy';
  54. const FORMAT_DATE_XLSX16 = 'd-mmm';
  55. const FORMAT_DATE_XLSX17 = 'mmm-yy';
  56. const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm';
  57. const FORMAT_DATE_DATETIME = 'd/m/y h:mm';
  58. const FORMAT_DATE_TIME1 = 'h:mm AM/PM';
  59. const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM';
  60. const FORMAT_DATE_TIME3 = 'h:mm';
  61. const FORMAT_DATE_TIME4 = 'h:mm:ss';
  62. const FORMAT_DATE_TIME5 = 'mm:ss';
  63. const FORMAT_DATE_TIME6 = 'h:mm:ss';
  64. const FORMAT_DATE_TIME7 = 'i:s.S';
  65. const FORMAT_DATE_TIME8 = 'h:mm:ss;@';
  66. const FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@';
  67. const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-';
  68. const FORMAT_CURRENCY_USD = '$#,##0_-';
  69. const FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-';
  70. /**
  71. * Excel built-in number formats
  72. *
  73. * @var array
  74. */
  75. protected static $_builtInFormats;
  76. /**
  77. * Excel built-in number formats (flipped, for faster lookups)
  78. *
  79. * @var array
  80. */
  81. protected static $_flippedBuiltInFormats;
  82. /**
  83. * Format Code
  84. *
  85. * @var string
  86. */
  87. protected $_formatCode = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  88. /**
  89. * Built-in format Code
  90. *
  91. * @var string
  92. */
  93. protected $_builtInFormatCode = 0;
  94. /**
  95. * Create a new PHPExcel_Style_NumberFormat
  96. *
  97. * @param boolean $isSupervisor Flag indicating if this is a supervisor or not
  98. * Leave this value at default unless you understand exactly what
  99. * its ramifications are
  100. * @param boolean $isConditional Flag indicating if this is a conditional style or not
  101. * Leave this value at default unless you understand exactly what
  102. * its ramifications are
  103. */
  104. public function __construct($isSupervisor = FALSE, $isConditional = FALSE)
  105. {
  106. // Supervisor?
  107. parent::__construct($isSupervisor);
  108. if ($isConditional) {
  109. $this->_formatCode = NULL;
  110. }
  111. }
  112. /**
  113. * Get the shared style component for the currently active cell in currently active sheet.
  114. * Only used for style supervisor
  115. *
  116. * @return PHPExcel_Style_NumberFormat
  117. */
  118. public function getSharedComponent()
  119. {
  120. return $this->_parent->getSharedComponent()->getNumberFormat();
  121. }
  122. /**
  123. * Build style array from subcomponents
  124. *
  125. * @param array $array
  126. * @return array
  127. */
  128. public function getStyleArray($array)
  129. {
  130. return array('numberformat' => $array);
  131. }
  132. /**
  133. * Apply styles from array
  134. *
  135. * <code>
  136. * $objPHPExcel->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray(
  137. * array(
  138. * 'code' => PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE
  139. * )
  140. * );
  141. * </code>
  142. *
  143. * @param array $pStyles Array containing style information
  144. * @throws PHPExcel_Exception
  145. * @return PHPExcel_Style_NumberFormat
  146. */
  147. public function applyFromArray($pStyles = null)
  148. {
  149. if (is_array($pStyles)) {
  150. if ($this->_isSupervisor) {
  151. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
  152. } else {
  153. if (array_key_exists('code', $pStyles)) {
  154. $this->setFormatCode($pStyles['code']);
  155. }
  156. }
  157. } else {
  158. throw new PHPExcel_Exception("Invalid style array passed.");
  159. }
  160. return $this;
  161. }
  162. /**
  163. * Get Format Code
  164. *
  165. * @return string
  166. */
  167. public function getFormatCode()
  168. {
  169. if ($this->_isSupervisor) {
  170. return $this->getSharedComponent()->getFormatCode();
  171. }
  172. if ($this->_builtInFormatCode !== false)
  173. {
  174. return self::builtInFormatCode($this->_builtInFormatCode);
  175. }
  176. return $this->_formatCode;
  177. }
  178. /**
  179. * Set Format Code
  180. *
  181. * @param string $pValue
  182. * @return PHPExcel_Style_NumberFormat
  183. */
  184. public function setFormatCode($pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL)
  185. {
  186. if ($pValue == '') {
  187. $pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  188. }
  189. if ($this->_isSupervisor) {
  190. $styleArray = $this->getStyleArray(array('code' => $pValue));
  191. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
  192. } else {
  193. $this->_formatCode = $pValue;
  194. $this->_builtInFormatCode = self::builtInFormatCodeIndex($pValue);
  195. }
  196. return $this;
  197. }
  198. /**
  199. * Get Built-In Format Code
  200. *
  201. * @return int
  202. */
  203. public function getBuiltInFormatCode()
  204. {
  205. if ($this->_isSupervisor) {
  206. return $this->getSharedComponent()->getBuiltInFormatCode();
  207. }
  208. return $this->_builtInFormatCode;
  209. }
  210. /**
  211. * Set Built-In Format Code
  212. *
  213. * @param int $pValue
  214. * @return PHPExcel_Style_NumberFormat
  215. */
  216. public function setBuiltInFormatCode($pValue = 0)
  217. {
  218. if ($this->_isSupervisor) {
  219. $styleArray = $this->getStyleArray(array('code' => self::builtInFormatCode($pValue)));
  220. $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
  221. } else {
  222. $this->_builtInFormatCode = $pValue;
  223. $this->_formatCode = self::builtInFormatCode($pValue);
  224. }
  225. return $this;
  226. }
  227. /**
  228. * Fill built-in format codes
  229. */
  230. private static function fillBuiltInFormatCodes()
  231. {
  232. // Built-in format codes
  233. if (is_null(self::$_builtInFormats)) {
  234. self::$_builtInFormats = array();
  235. // General
  236. self::$_builtInFormats[0] = PHPExcel_Style_NumberFormat::FORMAT_GENERAL;
  237. self::$_builtInFormats[1] = '0';
  238. self::$_builtInFormats[2] = '0.00';
  239. self::$_builtInFormats[3] = '#,##0';
  240. self::$_builtInFormats[4] = '#,##0.00';
  241. self::$_builtInFormats[9] = '0%';
  242. self::$_builtInFormats[10] = '0.00%';
  243. self::$_builtInFormats[11] = '0.00E+00';
  244. self::$_builtInFormats[12] = '# ?/?';
  245. self::$_builtInFormats[13] = '# ??/??';
  246. self::$_builtInFormats[14] = 'mm-dd-yy';
  247. self::$_builtInFormats[15] = 'd-mmm-yy';
  248. self::$_builtInFormats[16] = 'd-mmm';
  249. self::$_builtInFormats[17] = 'mmm-yy';
  250. self::$_builtInFormats[18] = 'h:mm AM/PM';
  251. self::$_builtInFormats[19] = 'h:mm:ss AM/PM';
  252. self::$_builtInFormats[20] = 'h:mm';
  253. self::$_builtInFormats[21] = 'h:mm:ss';
  254. self::$_builtInFormats[22] = 'm/d/yy h:mm';
  255. self::$_builtInFormats[37] = '#,##0 ;(#,##0)';
  256. self::$_builtInFormats[38] = '#,##0 ;[Red](#,##0)';
  257. self::$_builtInFormats[39] = '#,##0.00;(#,##0.00)';
  258. self::$_builtInFormats[40] = '#,##0.00;[Red](#,##0.00)';
  259. self::$_builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)';
  260. self::$_builtInFormats[45] = 'mm:ss';
  261. self::$_builtInFormats[46] = '[h]:mm:ss';
  262. self::$_builtInFormats[47] = 'mmss.0';
  263. self::$_builtInFormats[48] = '##0.0E+0';
  264. self::$_builtInFormats[49] = '@';
  265. // CHT
  266. self::$_builtInFormats[27] = '[$-404]e/m/d';
  267. self::$_builtInFormats[30] = 'm/d/yy';
  268. self::$_builtInFormats[36] = '[$-404]e/m/d';
  269. self::$_builtInFormats[50] = '[$-404]e/m/d';
  270. self::$_builtInFormats[57] = '[$-404]e/m/d';
  271. // THA
  272. self::$_builtInFormats[59] = 't0';
  273. self::$_builtInFormats[60] = 't0.00';
  274. self::$_builtInFormats[61] = 't#,##0';
  275. self::$_builtInFormats[62] = 't#,##0.00';
  276. self::$_builtInFormats[67] = 't0%';
  277. self::$_builtInFormats[68] = 't0.00%';
  278. self::$_builtInFormats[69] = 't# ?/?';
  279. self::$_builtInFormats[70] = 't# ??/??';
  280. // Flip array (for faster lookups)
  281. self::$_flippedBuiltInFormats = array_flip(self::$_builtInFormats);
  282. }
  283. }
  284. /**
  285. * Get built-in format code
  286. *
  287. * @param int $pIndex
  288. * @return string
  289. */
  290. public static function builtInFormatCode($pIndex)
  291. {
  292. // Clean parameter
  293. $pIndex = intval($pIndex);
  294. // Ensure built-in format codes are available
  295. self::fillBuiltInFormatCodes();
  296. // Lookup format code
  297. if (isset(self::$_builtInFormats[$pIndex])) {
  298. return self::$_builtInFormats[$pIndex];
  299. }
  300. return '';
  301. }
  302. /**
  303. * Get built-in format code index
  304. *
  305. * @param string $formatCode
  306. * @return int|boolean
  307. */
  308. public static function builtInFormatCodeIndex($formatCode)
  309. {
  310. // Ensure built-in format codes are available
  311. self::fillBuiltInFormatCodes();
  312. // Lookup format code
  313. if (isset(self::$_flippedBuiltInFormats[$formatCode])) {
  314. return self::$_flippedBuiltInFormats[$formatCode];
  315. }
  316. return false;
  317. }
  318. /**
  319. * Get hash code
  320. *
  321. * @return string Hash code
  322. */
  323. public function getHashCode()
  324. {
  325. if ($this->_isSupervisor) {
  326. return $this->getSharedComponent()->getHashCode();
  327. }
  328. return md5(
  329. $this->_formatCode
  330. . $this->_builtInFormatCode
  331. . __CLASS__
  332. );
  333. }
  334. /**
  335. * Search/replace values to convert Excel date/time format masks to PHP format masks
  336. *
  337. * @var array
  338. */
  339. private static $_dateFormatReplacements = array(
  340. // first remove escapes related to non-format characters
  341. '\\' => '',
  342. // 12-hour suffix
  343. 'am/pm' => 'A',
  344. // 4-digit year
  345. 'e' => 'Y',
  346. 'yyyy' => 'Y',
  347. // 2-digit year
  348. 'yy' => 'y',
  349. // first letter of month - no php equivalent
  350. 'mmmmm' => 'M',
  351. // full month name
  352. 'mmmm' => 'F',
  353. // short month name
  354. 'mmm' => 'M',
  355. // mm is minutes if time, but can also be month w/leading zero
  356. // so we try to identify times be the inclusion of a : separator in the mask
  357. // It isn't perfect, but the best way I know how
  358. ':mm' => ':i',
  359. 'mm:' => 'i:',
  360. // month leading zero
  361. 'mm' => 'm',
  362. // month no leading zero
  363. 'm' => 'n',
  364. // full day of week name
  365. 'dddd' => 'l',
  366. // short day of week name
  367. 'ddd' => 'D',
  368. // days leading zero
  369. 'dd' => 'd',
  370. // days no leading zero
  371. 'd' => 'j',
  372. // seconds
  373. 'ss' => 's',
  374. // fractional seconds - no php equivalent
  375. '.s' => ''
  376. );
  377. /**
  378. * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock)
  379. *
  380. * @var array
  381. */
  382. private static $_dateFormatReplacements24 = array(
  383. 'hh' => 'H',
  384. 'h' => 'G'
  385. );
  386. /**
  387. * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock)
  388. *
  389. * @var array
  390. */
  391. private static $_dateFormatReplacements12 = array(
  392. 'hh' => 'h',
  393. 'h' => 'g'
  394. );
  395. private static function _formatAsDate(&$value, &$format)
  396. {
  397. // dvc: convert Excel formats to PHP date formats
  398. // strip off first part containing e.g. [$-F800] or [$USD-409]
  399. // general syntax: [$<Currency string>-<language info>]
  400. // language info is in hexadecimal
  401. $format = preg_replace('/^(\[\$[A-Z]*-[0-9A-F]*\])/i', '', $format);
  402. // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case
  403. $format = strtolower($format);
  404. $format = strtr($format,self::$_dateFormatReplacements);
  405. if (!strpos($format,'A')) { // 24-hour time format
  406. $format = strtr($format,self::$_dateFormatReplacements24);
  407. } else { // 12-hour time format
  408. $format = strtr($format,self::$_dateFormatReplacements12);
  409. }
  410. $dateObj = PHPExcel_Shared_Date::ExcelToPHPObject($value);
  411. $value = $dateObj->format($format);
  412. }
  413. private static function _formatAsPercentage(&$value, &$format)
  414. {
  415. if ($format === self::FORMAT_PERCENTAGE) {
  416. $value = round( (100 * $value), 0) . '%';
  417. } else {
  418. if (preg_match('/\.[#0]+/i', $format, $m)) {
  419. $s = substr($m[0], 0, 1) . (strlen($m[0]) - 1);
  420. $format = str_replace($m[0], $s, $format);
  421. }
  422. if (preg_match('/^[#0]+/', $format, $m)) {
  423. $format = str_replace($m[0], strlen($m[0]), $format);
  424. }
  425. $format = '%' . str_replace('%', 'f%%', $format);
  426. $value = sprintf($format, 100 * $value);
  427. }
  428. }
  429. private static function _formatAsFraction(&$value, &$format)
  430. {
  431. $sign = ($value < 0) ? '-' : '';
  432. $integerPart = floor(abs($value));
  433. $decimalPart = trim(fmod(abs($value),1),'0.');
  434. $decimalLength = strlen($decimalPart);
  435. $decimalDivisor = pow(10,$decimalLength);
  436. $GCD = PHPExcel_Calculation_MathTrig::GCD($decimalPart,$decimalDivisor);
  437. $adjustedDecimalPart = $decimalPart/$GCD;
  438. $adjustedDecimalDivisor = $decimalDivisor/$GCD;
  439. if ((strpos($format,'0') !== false) || (strpos($format,'#') !== false) || (substr($format,0,3) == '? ?')) {
  440. if ($integerPart == 0) {
  441. $integerPart = '';
  442. }
  443. $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor";
  444. } else {
  445. $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor;
  446. $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor";
  447. }
  448. }
  449. private static function _complexNumberFormatMask($number, $mask) {
  450. if (strpos($mask,'.') !== false) {
  451. $numbers = explode('.', $number . '.0');
  452. $masks = explode('.', $mask . '.0');
  453. $result1 = self::_complexNumberFormatMask($numbers[0], $masks[0]);
  454. $result2 = strrev(self::_complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1])));
  455. return $result1 . '.' . $result2;
  456. }
  457. $r = preg_match_all('/0+/', $mask, $result, PREG_OFFSET_CAPTURE);
  458. if ($r > 1) {
  459. $result = array_reverse($result[0]);
  460. foreach($result as $block) {
  461. $divisor = 1 . $block[0];
  462. $size = strlen($block[0]);
  463. $offset = $block[1];
  464. $blockValue = sprintf(
  465. '%0' . $size . 'd',
  466. fmod($number, $divisor)
  467. );
  468. $number = floor($number / $divisor);
  469. $mask = substr_replace($mask,$blockValue, $offset, $size);
  470. }
  471. if ($number > 0) {
  472. $mask = substr_replace($mask, $number, $offset, 0);
  473. }
  474. $result = $mask;
  475. } else {
  476. $result = $number;
  477. }
  478. return $result;
  479. }
  480. /**
  481. * Convert a value in a pre-defined format to a PHP string
  482. *
  483. * @param mixed $value Value to format
  484. * @param string $format Format code
  485. * @param array $callBack Callback function for additional formatting of string
  486. * @return string Formatted string
  487. */
  488. public static function toFormattedString($value = '0', $format = PHPExcel_Style_NumberFormat::FORMAT_GENERAL, $callBack = null)
  489. {
  490. // For now we do not treat strings although section 4 of a format code affects strings
  491. if (!is_numeric($value)) return $value;
  492. // For 'General' format code, we just pass the value although this is not entirely the way Excel does it,
  493. // it seems to round numbers to a total of 10 digits.
  494. if (($format === PHPExcel_Style_NumberFormat::FORMAT_GENERAL) || ($format === PHPExcel_Style_NumberFormat::FORMAT_TEXT)) {
  495. return $value;
  496. }
  497. // Get the sections, there can be up to four sections
  498. $sections = explode(';', $format);
  499. // Fetch the relevant section depending on whether number is positive, negative, or zero?
  500. // Text not supported yet.
  501. // Here is how the sections apply to various values in Excel:
  502. // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT]
  503. // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE]
  504. // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO]
  505. // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT]
  506. switch (count($sections)) {
  507. case 1:
  508. $format = $sections[0];
  509. break;
  510. case 2:
  511. $format = ($value >= 0) ? $sections[0] : $sections[1];
  512. $value = abs($value); // Use the absolute value
  513. break;
  514. case 3:
  515. $format = ($value > 0) ?
  516. $sections[0] : ( ($value < 0) ?
  517. $sections[1] : $sections[2]);
  518. $value = abs($value); // Use the absolute value
  519. break;
  520. case 4:
  521. $format = ($value > 0) ?
  522. $sections[0] : ( ($value < 0) ?
  523. $sections[1] : $sections[2]);
  524. $value = abs($value); // Use the absolute value
  525. break;
  526. default:
  527. // something is wrong, just use first section
  528. $format = $sections[0];
  529. break;
  530. }
  531. // Save format with color information for later use below
  532. $formatColor = $format;
  533. // Strip color information
  534. $color_regex = '/^\\[[a-zA-Z]+\\]/';
  535. $format = preg_replace($color_regex, '', $format);
  536. // Let's begin inspecting the format and converting the value to a formatted string
  537. if (preg_match('/^(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy]/i', $format)) { // datetime format
  538. self::_formatAsDate($value, $format);
  539. } else if (preg_match('/%$/', $format)) { // % number format
  540. self::_formatAsPercentage($value, $format);
  541. } else {
  542. if ($format === self::FORMAT_CURRENCY_EUR_SIMPLE) {
  543. $value = 'EUR ' . sprintf('%1.2f', $value);
  544. } else {
  545. // In Excel formats, "_" is used to add spacing, which we can't do in HTML
  546. $format = preg_replace('/_./', '', $format);
  547. // Some non-number characters are escaped with \, which we don't need
  548. $format = preg_replace("/\\\\/", '', $format);
  549. // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols
  550. $format = str_replace(array('"','*'), '', $format);
  551. // Find out if we need thousands separator
  552. // This is indicated by a comma enclosed by a digit placeholder:
  553. // #,# or 0,0
  554. $useThousands = preg_match('/(#,#|0,0)/', $format);
  555. if ($useThousands) {
  556. $format = preg_replace('/0,0/', '00', $format);
  557. $format = preg_replace('/#,#/', '##', $format);
  558. }
  559. // Scale thousands, millions,...
  560. // This is indicated by a number of commas after a digit placeholder:
  561. // #, or 0.0,,
  562. $scale = 1; // same as no scale
  563. $matches = array();
  564. if (preg_match('/(#|0)(,+)/', $format, $matches)) {
  565. $scale = pow(1000, strlen($matches[2]));
  566. // strip the commas
  567. $format = preg_replace('/0,+/', '0', $format);
  568. $format = preg_replace('/#,+/', '#', $format);
  569. }
  570. if (preg_match('/#?.*\?\/\?/', $format, $m)) {
  571. //echo 'Format mask is fractional '.$format.' <br />';
  572. if ($value != (int)$value) {
  573. self::_formatAsFraction($value, $format);
  574. }
  575. } else {
  576. // Handle the number itself
  577. // scale number
  578. $value = $value / $scale;
  579. // Strip #
  580. $format = preg_replace('/\\#/', '0', $format);
  581. $n = "/\[[^\]]+\]/";
  582. $m = preg_replace($n, '', $format);
  583. $number_regex = "/(0+)(\.?)(0*)/";
  584. if (preg_match($number_regex, $m, $matches)) {
  585. $left = $matches[1];
  586. $dec = $matches[2];
  587. $right = $matches[3];
  588. // minimun width of formatted number (including dot)
  589. $minWidth = strlen($left) + strlen($dec) + strlen($right);
  590. if ($useThousands) {
  591. $value = number_format(
  592. $value
  593. , strlen($right)
  594. , PHPExcel_Shared_String::getDecimalSeparator()
  595. , PHPExcel_Shared_String::getThousandsSeparator()
  596. );
  597. $value = preg_replace($number_regex, $value, $format);
  598. } else {
  599. if (preg_match('/[0#]E[+-]0/i', $format)) {
  600. // Scientific format
  601. $value = sprintf('%5.2E', $value);
  602. } elseif (preg_match('/0([^\d\.]+)0/', $format)) {
  603. $value = self::_complexNumberFormatMask($value, $format);
  604. } else {
  605. $sprintf_pattern = "%0$minWidth." . strlen($right) . "f";
  606. $value = sprintf($sprintf_pattern, $value);
  607. $value = preg_replace($number_regex, $value, $format);
  608. }
  609. }
  610. }
  611. }
  612. if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
  613. // Currency or Accounting
  614. $currencyFormat = $m[0];
  615. $currencyCode = $m[1];
  616. list($currencyCode) = explode('-',$currencyCode);
  617. if ($currencyCode == '') {
  618. $currencyCode = PHPExcel_Shared_String::getCurrencyCode();
  619. }
  620. $value = preg_replace('/\[\$([^\]]*)\]/u',$currencyCode,$value);
  621. }
  622. }
  623. }
  624. // Additional formatting provided by callback function
  625. if ($callBack !== null) {
  626. list($writerInstance, $function) = $callBack;
  627. $value = $writerInstance->$function($value, $formatColor);
  628. }
  629. return $value;
  630. }
  631. }