Skip to content

Commit

Permalink
Fix ROUNDUP and ROUNDDOWN for floating-point rounding error (#1404)
Browse files Browse the repository at this point in the history
Closes #1404
  • Loading branch information
n-longcape authored Mar 7, 2020
1 parent a08415a commit a79b344
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ and this project adheres to [Semantic Versioning](https://semver.org).
- Fix active cell when freeze pane is used [#1323](https://github.com/PHPOffice/PhpSpreadsheet/pull/1323)
- Fix XLSX file loading with autofilter containing '$' [#1326](https://github.com/PHPOffice/PhpSpreadsheet/pull/1326)
- PHPDoc - Use `@return $this` for fluent methods [#1362](https://github.com/PHPOffice/PhpSpreadsheet/pull/1362)
- Fix ROUNDUP and ROUNDDOWN for floating-point rounding error [#1404](https://github.com/PHPOffice/PhpSpreadsheet/pull/1404)

## [1.10.1] - 2019-12-02

Expand Down
10 changes: 6 additions & 4 deletions src/PhpSpreadsheet/Calculation/MathTrig.php
Original file line number Diff line number Diff line change
Expand Up @@ -1064,12 +1064,13 @@ public static function ROUNDUP($number, $digits)
$digits = Functions::flattenSingleValue($digits);

if ((is_numeric($number)) && (is_numeric($digits))) {
$significance = pow(10, (int) $digits);
if ($number < 0.0) {
$significance = pow(10, (int) $digits);

return floor($number * $significance) / $significance;
}

return ceil($number * $significance) / $significance;
return round($number + 0.5 * pow(0.1, $digits), $digits, PHP_ROUND_HALF_DOWN);
}

return Functions::VALUE();
Expand All @@ -1091,12 +1092,13 @@ public static function ROUNDDOWN($number, $digits)
$digits = Functions::flattenSingleValue($digits);

if ((is_numeric($number)) && (is_numeric($digits))) {
$significance = pow(10, (int) $digits);
if ($number < 0.0) {
$significance = pow(10, (int) $digits);

return ceil($number * $significance) / $significance;
}

return floor($number * $significance) / $significance;
return round($number - 0.5 * pow(0.1, $digits), $digits, PHP_ROUND_HALF_UP);
}

return Functions::VALUE();
Expand Down
10 changes: 10 additions & 0 deletions tests/data/Calculation/MathTrig/ROUNDDOWN.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@
31415.92654,
-1,
],
[
4.44,
4.4400,
2,
],
[
5.20,
2.26 + 2.94,
2,
],
[
'#VALUE!',
'ABC',
Expand Down
10 changes: 10 additions & 0 deletions tests/data/Calculation/MathTrig/ROUNDUP.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@
31415.92654,
-1,
],
[
4.44,
4.4400,
2,
],
[
5.20,
2.26 + 2.94,
2,
],
[
'#VALUE!',
'ABC',
Expand Down

0 comments on commit a79b344

Please sign in to comment.