diff --git a/README.md b/README.md index 64d6317..800a562 100644 --- a/README.md +++ b/README.md @@ -51,14 +51,14 @@ Or can create Decimal objects from either strings or numbers using `decimal`: julia> decimal("-2.5e6") Decimal(1,25,5) -To convert back to a string or a float: +To convert back to a string or a number (float in this case): julia> x = decimal("0.2"); julia> string(x) "0.2" - julia> float(x) + julia> number(x) 0.2 It is also possible to call the Decimal constructor directly, by specifying the sign (`s`), coefficient (`c`), and exponent (`q`): diff --git a/src/arithmetic.jl b/src/arithmetic.jl index e729cc5..b23e6e2 100644 --- a/src/arithmetic.jl +++ b/src/arithmetic.jl @@ -30,13 +30,8 @@ end # Inversion function Base.inv(x::Decimal) - str = string(x) - if str[1] == '-' - str = str[2:end] - end - b = ('.' in str) ? length(split(str, '.')[1]) : 0 - c = round(BigInt(10)^(-x.q + DIGITS) / x.c) - q = (x.q < 0) ? 1 - b - DIGITS : -b - DIGITS + c = round(BigInt(10)^(-x.q + DIGITS) / x.c) # the decimal point of 1/x.c is shifted by -x.q so that the integer part of the result is correct and then it is shifted further by DIGITS to also cover some digits from the fractional part. + q = -DIGITS # we only need to remember that there are these digits after the decimal point normalize(Decimal(x.s, c, q)) end diff --git a/test/test_arithmetic.jl b/test/test_arithmetic.jl index f1a0edb..e21e772 100644 --- a/test/test_arithmetic.jl +++ b/test/test_arithmetic.jl @@ -46,6 +46,7 @@ end @test inv(Decimal(0, 5, 1)) == Decimal(0, 2, -2) @test inv(Decimal(1, 4, -1)) == Decimal(1, 25, -1) @test inv(Decimal(1, 25, -1)) == Decimal(1, 4, -1) + @test inv(Decimal(0, 123, -1)) == Decimal(0, 813008130081300813, -19) # 1/12.3 ≈ 0.08 end @testset "Division" begin