Skip to content

Commit

Permalink
Remove locale from format string to prevent formatting error (PHPOffi…
Browse files Browse the repository at this point in the history
…ce#644)

When a formatting string has a locale in it an error can occur when outputting. For example when the format string with a locale such as `[$-1010409]#,##0.00;-#,##0.00` appears, a value of 9.98 comes back as $9.98. This is because at https://github.com/PHPOffice/PhpSpreadsheet/blob/1.4.0/src/PhpSpreadsheet/Style/NumberFormat.php#L711 the numberFormat regex will match to the zeros inside the locale ([$-1010409]). Attempts to adjust the numberFormat regex caused regressions in other tests. Adding another step to filter out the locale caused no regression.
  • Loading branch information
deekthesqueak authored and Frederic Delaunay committed Oct 29, 2018
1 parent e50e1f9 commit 303b0ec
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]

- Remove locale from formatting string - [#644](https://github.com/PHPOffice/PhpSpreadsheet/pull/644)


### Fixed

- Allow iterators to go out of bounds with prev - [#587](https://github.com/PHPOffice/PhpSpreadsheet/issues/587)
Expand Down
3 changes: 3 additions & 0 deletions src/PhpSpreadsheet/Style/NumberFormat.php
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,9 @@ public static function toFormattedString($value, $format, $callBack = null)
// Strip #
$format = preg_replace('/\\#/', '0', $format);

// Remove locale code [$-###]
$format = preg_replace('/\[\$\-.*\]/', '', $format);

$n = '/\\[[^\\]]+\\]/';
$m = preg_replace($n, '', $format);
$number_regex = '/(0+)(\\.?)(0*)/';
Expand Down
20 changes: 20 additions & 0 deletions tests/data/Style/NumberFormat.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,4 +186,24 @@
-1234567.8899999999,
'0000:00.00',
],
[
'18.952',
18.952,
'[$-409]General',
],
[
'9.98',
9.98,
'[$-409]#,##0.00;-#,##0.00',
],
[
'18.952',
18.952,
'[$-1010409]General',
],
[
'9.98',
9.98,
'[$-1010409]#,##0.00;-#,##0.00',
],
];
10 changes: 10 additions & 0 deletions tests/data/Style/NumberFormatDates.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,14 @@
43270.603472222,
'hh:mm:ss\ AM/PM',
],
[
'8/20/2018',
43332,
'[$-409]m/d/yyyy',
],
[
'8/20/2018',
43332,
'[$-1010409]m/d/yyyy',
],
];

0 comments on commit 303b0ec

Please sign in to comment.