Skip to content
This repository has been archived by the owner on Jan 2, 2019. It is now read-only.

added basic support of # (optional number) for decimals #746

Open
wants to merge 1 commit into
base: 1.8
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Classes/PHPExcel/Style/NumberFormat.php
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ private static function fillBuiltInFormatCodes()
// 40: "#,##0.00_);[Red](#,##0.00)"
// 47: "mm:ss.0"
// KOR fmt 55: "yyyy/mm/dd"

// Built-in format codes
if (is_null(self::$builtInFormats)) {
self::$builtInFormats = array();
Expand Down Expand Up @@ -689,6 +689,8 @@ public static function toFormattedString($value = '0', $format = PHPExcel_Style_
// scale number
$value = $value / $scale;

$decimalsFormat = strstr($format, '.');
$optionalDecimalsCount = strlen($decimalsFormat) - strlen(rtrim($decimalsFormat, '#'));
// Strip #
$format = preg_replace('/\\#/', '0', $format);

Expand Down Expand Up @@ -723,6 +725,11 @@ public static function toFormattedString($value = '0', $format = PHPExcel_Style_
}
}
}

while ($optionalDecimalsCount > 0 && substr($value, -1) === '0') {
$value = substr($value, 0, -1);
$optionalDecimalsCount--;
}
}
if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
// Currency or Accounting
Expand Down
14 changes: 13 additions & 1 deletion unitTests/rawTestData/Style/NumberFormat.data
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
0.1, "0.0", "0.1"
0.1, "0", "0"
5.5555, "0.###", "5.556"
5.5555, "0.0##", "5.556"
5.5555, "0.0##", "5.556"
5.5555, "0.00#", "5.556"
5.5555, "0.000", "5.556"
5.5555, "0.0000", "5.5555"
Expand All @@ -35,3 +35,15 @@
-123456789, '0000:00:00', "-12345:67:89"
1234567.89, '0000:00.00', "12345:67.89"
-1234567.89,'0000:00.00', "-12345:67.89"
12345.6789, '"#,##0.##"', '"12,345.68"' // test case from above
12345.6, '"#,##0.00"', '"12,345.60"' // 0 means: show decimal
12345.6, '"#,##0.##"', '"12,345.6"' // # means: "cut off zeros"
12345, '"#,##0.00"', '"12,345.00"' // 0 means: show decimal
12345, '"#,##0.##"', '"12,345."' // # means: "cut off zeros" (decimal separator can not be made optional by excel)
12345.6789, '"#,##0.0#"', '"12,345.68"' // first not optional, second optional
12345.6, '"#,##0.0#"', '"12,345.6"' // first not optional, second optional
12345, '"#,##0.0#"', '"12,345.0"' // first not optional, second optional
12345.6789, '"#,##0.000#"', '"12,345.6789"'
12345.6, '"#,##0.000#"', '"12,345.600"'
12345.6789, '"#,##0.0#0#"', '"12,345.6789"' // treated like .000#
12345.6, '"#,##0.0#0#"', '"12,345.600"' // treated like .000#