Skip to content

Commit 2633540

Browse files
committed
Fix convert at the input limits
Using an `@eval` in the tests to make it clear what `T` and `f` caused the failure.
1 parent 031543c commit 2633540

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

src/FixedPointDecimals.jl

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -190,11 +190,11 @@ for fn in [:trunc, :floor, :ceil]
190190
reinterpret(FD{T, f}, val)
191191
end
192192
end
193-
round{TI <: Integer}(::Type{TI}, x::FD,
194-
::RoundingMode{:Nearest}=RoundNearest)::TI = round(x)
195-
function round{T, f}(::Type{FD{T, f}}, x::Real,
196-
::RoundingMode{:Nearest}=RoundNearest)
197-
reinterpret(FD{T, f}, round(T, T(10)^f * x))
193+
function round{TI <: Integer}(::Type{TI}, x::FD, ::RoundingMode{:Nearest}=RoundNearest)::TI
194+
round(x)
195+
end
196+
function round{T, f}(::Type{FD{T, f}}, x::Real, ::RoundingMode{:Nearest}=RoundNearest)
197+
reinterpret(FD{T, f}, round(T, x * coefficient(FD{T, f})))
198198
end
199199

200200
# needed to avoid ambiguity

test/runtests.jl

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,26 @@ end
9393
end
9494
end
9595

96+
@testset "limits" begin
97+
for T in CONTAINER_TYPES
98+
f = FixedPointDecimals.max_exp10(T) + 1
99+
powt = FixedPointDecimals.coefficient(FD{T,f})
100+
101+
# ideally we would just use `typemax(T)` but due to precision issues with
102+
# floating-point its possible the closest float will exceed `typemax(T)`.
103+
# Note: we should be doing `trunc(T, ...)` but truncating a BigFloat can be
104+
# problematic (https://github.com/JuliaLang/julia/issues/21914)
105+
max_int = trunc(BigInt, prevfloat(typemax(T) / powt) * powt)
106+
min_int = trunc(BigInt, nextfloat(typemin(T) / powt) * powt)
107+
@eval begin
108+
@test $max_int <= typemax($T)
109+
@test convert(FD{$T,$f}, $(max_int / powt)).i == $max_int
110+
@test $min_int >= typemin($T)
111+
@test convert(FD{$T,$f}, $(min_int / powt)).i == $min_int
112+
end
113+
end
114+
end
115+
96116
@test_throws InexactError convert(FD2, FD4(0.0001))
97117
@test_throws InexactError convert(FD4, typemax(FD2))
98118
@test_throws InexactError convert(SFD2, typemax(FD2))

0 commit comments

Comments
 (0)