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

Catching 'Divide By Zero Error' and Formatting #8

Open
jamesmills opened this issue Oct 5, 2021 · 4 comments
Open

Catching 'Divide By Zero Error' and Formatting #8

jamesmills opened this issue Oct 5, 2021 · 4 comments

Comments

@jamesmills
Copy link

Howdy @mattiasgeniar

Firstly, thanks for this package, saved me some time!

Nothing urgent here... I just found myself having to wrap around your function with the below to catch and format. Not sure if this is helpful for any additional feature ideas or not but thought I would share anyway.

    function percentageWrapper($a, $b, $round = true, $symbol = true)
    {
        if ($a <= 0 || $b <= 0) {
            $percentage = 0;
        } else {
            $percentage = percentage($a, $b);
        }

        if ($round) {
            $percentage = round($percentage);
        }

        if ($symbol) {
            $percentage .= '%';
        }

        return $percentage;
    }
@robertmylne
Copy link

robertmylne commented Nov 18, 2021

    function percentageWrapper($a, $b, $decimals = null, $symbol = true)
    {
        if ($a == 0 || $b == 0) { // <--- we need to allow negative changes, example is stock investing.
            $percentage = 0;
        } else {
            $percentage = percentage($a, $b);
        }

        if ($decimals) {
            $percentage = ($decimals === 0) ? intval(round($percentage, decimals))  : round($percentage, decimals); // <-- allows dynamic choice of decimal places and defaults to resulting decimal places.
        }

        if ($symbol) {
            $percentage .= '%';
        }

        return $percentage;
    }

@jamesmills
Copy link
Author

jamesmills commented Nov 22, 2021

Shall I PR this? Or can you think of a better function name for it to fit with the package?

@intrepidws
Copy link

Did anything ever come of this? I'm running into the same troubles.

@mattiasgeniar
Copy link
Owner

Happy to accept a PR for this, although I'm not 100% sure what the idea end result is: if you divide by zero, it's invalid, should it just return 0? Or throw an exception to catch further down? The exception doesn't really solve the problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants