Skip to content

ROUNDDOWN and ROUNDUP return incorrect results for values of 0 #1626

@Flinsch

Description

@Flinsch

This is:

- [X] a bug report
- [ ] a feature request
- [X] **not** a usage question (ask them on https://stackoverflow.com/questions/tagged/phpspreadsheet or https://gitter.im/PHPOffice/PhpSpreadsheet)

What is the expected behavior?

Values of 0 should stay 0 when either rounded up or down.

What is the current behavior?

Values of 0 are "rounded" down/up as if they were not 0.

What are the steps to reproduce?

The following code produces output -0.01 0.01 instead of 0 0:

<?php

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

echo \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ROUNDDOWN(0, 2).' ';
echo \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::ROUNDUP(0, 2).' ';

What could be a possible solution?

A possible solution could be to explicitly handle values of zero. In ROUNDUP, for example, the code could be something like this:

        if ((is_numeric($number)) && (is_numeric($digits))) {
            if ($number == 0.0) {
                return 0.0;
            }

            if ($number < 0.0) {
                return round($number - 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_DOWN);
            }

            return round($number + 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_DOWN);
        }

Which versions of PhpSpreadsheet and PHP are affected?

PhpSpreadsheet 1.14.1
PHP 7.2.20

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions