Skip to content

Commit 9fde399

Browse files
authored
Fix rounding in division (#100)
1 parent 4638697 commit 9fde399

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

src/arithmetic.jl

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -201,12 +201,18 @@ function Base.:(/)(x::Decimal, y::Decimal)
201201

202202
if d > 0
203203
# If `d` is positive, we take the path denoted (P1)
204-
c = div(x.c * BigTen^d, y.c)
204+
c, rem = divrem(x.c * BigTen^d, y.c)
205205
elseif d < 0
206206
# If `d` is negative, we take the path denoted (P2)
207-
c = div(x.c, y.c * BigTen^(-d))
207+
c, rem = divrem(x.c, y.c * BigTen^(-d))
208208
else
209-
c = div(x.c, y.c)
209+
c, rem = divrem(x.c, y.c)
210+
end
211+
212+
# When the result is non-exact, and the last coefficient digit is 5, we
213+
# need to increment the coefficient for correct rounding
214+
if rem > 0 && isdivisible(c, 5)
215+
c += 1
210216
end
211217

212218
return fix(Decimal(s, c, q))

test/test_arithmetic.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,7 @@ using Test
7373
@with_context (Emax=999, Emin=-999, precision=9, rounding=RoundNearestTiesAway) @test inv(dec"2") == dec"0.5"
7474
end
7575

76+
Decimals.@with_context (precision=2, rounding=RoundNearest) @test dec"10500000" / dec"10000" == Decimal(0, 10, 2)
77+
Decimals.@with_context (precision=2, rounding=RoundNearest) @test dec"10500009" / dec"10000" == Decimal(0, 11, 2)
78+
7679
end

0 commit comments

Comments
 (0)