diff --git a/Project.toml b/Project.toml index 27f3f9f..c010e17 100644 --- a/Project.toml +++ b/Project.toml @@ -4,11 +4,13 @@ authors = ["Fengyang Wang ", "Curtis Vogt = v"1.6" + function Base.round(::Type{FD{T, f}}, x::Rational{Tr}, ::RoundingMode{:Nearest}=RoundNearest) where {T, Tr, f} + reinterpret(FD{T, f}, round(T, x * coefficient(FD{T, f}))) + end +else # COV_EXCL_START + function Base.round(::Type{FD{T, f}}, x::Rational, ::RoundingMode{:Nearest}=RoundNearest) where {T, f} + reinterpret(FD{T, f}, round(T, x * coefficient(FD{T, f}))) + end +end # COV_EXCL_STOP +function Base.round(::Type{FD{T, f}}, x::Rational{Bool}, ::RoundingMode{:Nearest}=RoundNearest) where {T, f} reinterpret(FD{T, f}, round(T, x * coefficient(FD{T, f}))) end @@ -325,6 +347,8 @@ function Base.convert(::Type{TR}, x::FD{T, f}) where {TR <: Rational, T, f} end (::Type{T})(x::FD) where {T<:Union{AbstractFloat,Integer,Rational}} = convert(T, x) +# needed to avoid ambiguities +Bool(x::FD) = x == 0 ? false : (x == 1 ? true : throw(InexactError(:Bool, Bool, x))) Base.promote_rule(::Type{FD{T, f}}, ::Type{<:Integer}) where {T, f} = FD{T, f} Base.promote_rule(::Type{<:FD}, ::Type{TF}) where {TF <: AbstractFloat} = TF diff --git a/test/runtests.jl b/test/runtests.jl index 230a021..a77ad83 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1045,4 +1045,24 @@ end end end +@testset "method ambiguities" begin + fd1 = FD{Int8, 1}(0.1) + fd2 = FD{Int, 1}(1.0) + + @test widemul(fd1, false) == widemul(false, fd1) == FD{Int8, 1}(0.0) + @test ceil(FD{Int, 1}, 99 // 100) == fd2 + @test round(FD{Int, 1}, true // true) == fd2 + @test invoke(round, Tuple{Type{FD{Int, 1}}, Rational}, FD{Int, 1}, 99 // 100) == fd2 + + @test Bool(fd2) + @test_throws InexactError Bool(fd1) +end + +@static if Base.VERSION >= v"1.6" + using Aqua + @testset "Aqua.jl" begin + Aqua.test_all(FixedPointDecimals) + end +end + end # global testset