Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ROUNDUP and ROUNDDOWN for floating-point rounding error #1404

Merged
merged 2 commits into from
Mar 7, 2020

Conversation

n-longcape
Copy link
Contributor

@n-longcape n-longcape commented Mar 3, 2020

This is:

- [x] a bugfix

Checklist:

Why this change is needed?

ROUNDUP and ROUNDDOWN are often different from Excel calculation result because of Floating point precision. PHP Official Document

example

I expected =ROUNDUP(SUM(2.21,2.19), 2) equals 4.4 but 4.41 and =ROUNDDOWN(SUM(2.26,2.94),2) equals 5.2 but 5.19

<?php

require __DIR__ . '/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;

$excel = new Spreadsheet();
$sheet = $excel->getActiveSheet();

// Sample Data
$sheet->setCellValue('A1', '2.21');
$sheet->setCellValue('A2', '2.19');
$sheet->setCellValue('A3', '2.26');
$sheet->setCellValue('A4', '2.94');

$sheet->setCellValue('B1', '=ROUNDUP(SUM(A1:A2), 2)');
$result = $sheet->getCell('B1')->getFormattedValue();
var_dump($result); // "4.41" 
var_dump(number_format(2.21 + 2.19, 20)); // "4.40000000000000035527"

$sheet->setCellValue('B2', '=ROUNDDOWN(SUM(A3:A4),2)');
$result2 = $sheet->getCell('B2')->getFormattedValue();
var_dump($result2); // 5.19
var_dump(number_format(2.26 + 2.94, 20)); // "5.19999999999999928946"
var_dump(number_format(5.2, 20)); // "5.20000000000000017764"

@PowerKiKi PowerKiKi merged commit a79b344 into PHPOffice:master Mar 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants