Fix error in PercentageFormatter rounding (#2555)

* fix error in rounding percentages

* add tests for FORMAT_PERCENTAGE

* fix code style
This commit is contained in:
Sebastian Nohn 2022-02-05 21:19:05 +01:00 committed by GitHub
parent fe169dcd0a
commit b5c03fc61f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 125 additions and 2 deletions

View File

@ -44,6 +44,7 @@ and this project adheres to [Semantic Versioning](https://semver.org).
### Fixed
- Fix rounding error in NumberFormat::NUMBER_PERCENTAGE, NumberFormat::NUMBER_PERCENTAGE_00
- Fix partial function name matching when translating formulae from Russian to English [Issue #2533](https://github.com/PHPOffice/PhpSpreadsheet/issues/2533) [PR #2534](https://github.com/PHPOffice/PhpSpreadsheet/pull/2534)
- Various bugs related to Conditional Formatting Rules, and errors in the Xlsx Writer for Conditional Formatting [PR #2491](https://github.com/PHPOffice/PhpSpreadsheet/pull/2491)
- Xlsx Reader merge range fixes.

View File

@ -37,6 +37,9 @@ class PercentageFormatter extends BaseFormatter
$replacement = "{$wholePartSize}.{$decimalPartSize}";
$mask = preg_replace('/[#0,]+\.?[?#0,]*/ui', "%{$replacement}f{$placeHolders}", $format);
return sprintf($mask, $value);
/** @var float */
$valueFloat = $value;
return sprintf($mask, round($valueFloat, $decimalPartSize));
}
}

View File

@ -771,7 +771,126 @@ return [
'-1111.119',
NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2,
],
// Tests for FORMAT_PERCENTAGE, FORMAT_PERCENTAGE_00 currently fail. Fix & tests will be provided in #2555
[
'0%',
'0',
NumberFormat::FORMAT_PERCENTAGE,
],
[
'1%',
'0.01',
NumberFormat::FORMAT_PERCENTAGE,
],
[
'1%',
'0.011',
NumberFormat::FORMAT_PERCENTAGE,
],
[
'1%',
'0.014',
NumberFormat::FORMAT_PERCENTAGE,
],
[
'2%',
'0.015',
NumberFormat::FORMAT_PERCENTAGE,
],
[
'2%',
'0.019',
NumberFormat::FORMAT_PERCENTAGE,
],
[
'0%',
'-0',
NumberFormat::FORMAT_PERCENTAGE,
],
[
'-1%',
'-0.01',
NumberFormat::FORMAT_PERCENTAGE,
],
[
'-1%',
'-0.011',
NumberFormat::FORMAT_PERCENTAGE,
],
[
'-1%',
'-0.014',
NumberFormat::FORMAT_PERCENTAGE,
],
[
'-2%',
'-0.015',
NumberFormat::FORMAT_PERCENTAGE,
],
[
'-2%',
'-0.019',
NumberFormat::FORMAT_PERCENTAGE,
],
[
'0.00%',
'0',
NumberFormat::FORMAT_PERCENTAGE_00,
],
[
'1.00%',
'0.01',
NumberFormat::FORMAT_PERCENTAGE_00,
],
[
'1.11%',
'0.0111',
NumberFormat::FORMAT_PERCENTAGE_00,
],
[
'1.11%',
'0.01114',
NumberFormat::FORMAT_PERCENTAGE_00,
],
[
'1.12%',
'0.01115',
NumberFormat::FORMAT_PERCENTAGE_00,
],
[
'1.12%',
'0.01119',
NumberFormat::FORMAT_PERCENTAGE_00,
],
[
'0.00%',
'-0',
NumberFormat::FORMAT_PERCENTAGE_00,
],
[
'-1.00%',
'-0.01',
NumberFormat::FORMAT_PERCENTAGE_00,
],
[
'-1.11%',
'-0.0111',
NumberFormat::FORMAT_PERCENTAGE_00,
],
[
'-1.11%',
'-0.01114',
NumberFormat::FORMAT_PERCENTAGE_00,
],
[
'-1.12%',
'-0.01115',
NumberFormat::FORMAT_PERCENTAGE_00,
],
[
'-1.12%',
'-0.01119',
NumberFormat::FORMAT_PERCENTAGE_00,
],
[
'$0.00 ',
'0',