Skip to content

Return an error for division by zero in DecimalArithmetic - #124

Open
JayOfTheKeyboard wants to merge 1 commit into
PaesslerAG:masterfrom
JayOfTheKeyboard:decimal-zero-divisor
Open

JayOfTheKeyboard wants to merge 1 commit into
PaesslerAG:masterfrom
JayOfTheKeyboard:decimal-zero-divisor

Conversation

@JayOfTheKeyboard

Copy link
Copy Markdown

Fixes #123

What

With DecimalArithmetic(), 1 / 0, 1 % 0 and 0 ** (0 - 1) panicked inside shopspring/decimal, and the panic escaped Evaluate. They now return a division by zero error.

Fix

The decimal / and % operators check for a zero divisor before calling Div and Mod. ** returns the same error when the base is zero and the exponent is negative, because Pow divides by the base there.

This changes one result: 0 ** (0 - 0.5) used to return 1, since Pow in decimal v1.3.1 only looks at the integer part of the exponent. It now returns the error like the other negative powers of zero.

Constant expressions are folded while parsing, so 1 / 0 is reported as a parsing error. With parameters, x / y is an evaluation error.

Tests

TestDecimalArithmeticZeroDivisor covers each operator with literals and with parameters, plus cases that must keep working (0 / 4, 0 % 4, 2 ** (0 - 1), 0 ** 0). On master the test panics at the first case. With the fix, go test ./... passes.

shopspring/decimal panics when Div or Mod gets a zero divisor, and Pow
divides by the base for exponents of -1 or less. The panic escaped
Evaluate, so 1 / 0, 1 % 0 or 0 ** (0 - 1) crashed the caller when
DecimalArithmetic was enabled. Check for these cases and return an
error instead.
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

Successfully merging this pull request may close these issues.

DecimalArithmetic panics on division or modulo by zero

1 participant