diff --git a/base/float.jl b/base/float.jl index 8d7381ce3be4aa..60850b7e02f64a 100644 --- a/base/float.jl +++ b/base/float.jl @@ -358,6 +358,12 @@ floor(::Type{T}, x::AbstractFloat) where {T<:Integer} = trunc(T,round(x, RoundDo ceil(::Type{T}, x::AbstractFloat) where {T<:Integer} = trunc(T,round(x, RoundUp)) round(::Type{T}, x::AbstractFloat) where {T<:Integer} = trunc(T,round(x, RoundNearest)) +# Bool +trunc(::Type{Bool}, x::AbstractFloat) = (-1 < x < 2) ? 1 <= x : throw(InexactError(:trunc, Bool, x)) +floor(::Type{Bool}, x::AbstractFloat) = (0 <= x < 2) ? 1 <= x : throw(InexactError(:floor, Bool, x)) +ceil(::Type{Bool}, x::AbstractFloat) = (-1 < x <= 1) ? 0 < x : throw(InexactError(:ceil, Bool, x)) +round(::Type{Bool}, x::AbstractFloat) = (-0.5 <= x < 1.5) ? 0.5 < x : throw(InexactError(:round, Bool, x)) + round(x::IEEEFloat, r::RoundingMode{:ToZero}) = trunc_llvm(x) round(x::IEEEFloat, r::RoundingMode{:Down}) = floor_llvm(x) round(x::IEEEFloat, r::RoundingMode{:Up}) = ceil_llvm(x) diff --git a/test/numbers.jl b/test/numbers.jl index 149b34633fb8a8..dbc14609a502fd 100644 --- a/test/numbers.jl +++ b/test/numbers.jl @@ -2813,3 +2813,45 @@ end @test_throws MethodError fld(a, b) @test_throws MethodError cld(a, b) end + +@testset "Bool rounding (#25074)" begin + @testset "round Bool" begin + @test_throws InexactError round(Bool, -4.1) + @test_throws InexactError round(Bool, 1.5) + @test true == round(Bool, 1.0) + @test false == round(Bool, 0.0) + @test true == round(Bool, 0.6) + @test false == round(Bool, 0.4) + @test false == round(Bool, 0.5) + @test false == round(Bool, -0.5) + end + + @testset "trunc Bool" begin + @test_throws InexactError trunc(Bool, -4.1) + @test_throws InexactError trunc(Bool, 2.5) + @test true == trunc(Bool, 1.0) + @test false == trunc(Bool, 0.0) + @test false == trunc(Bool, 0.6) + @test false == trunc(Bool, 0.4) + @test true == trunc(Bool, 1.8) + @test false == trunc(Bool, -0.5) + end + + @testset "floor Bool" begin + @test_throws InexactError floor(Bool, -0.1) + @test_throws InexactError floor(Bool, 2.5) + @test true == floor(Bool, 1.0) + @test false == floor(Bool, 0.0) + @test false == floor(Bool, 0.6) + @test true == floor(Bool, 1.8) + end + + @testset "ceil Bool" begin + @test_throws InexactError ceil(Bool, -1.4) + @test_throws InexactError ceil(Bool, 1.5) + @test true == ceil(Bool, 1.0) + @test false == ceil(Bool, 0.0) + @test true == ceil(Bool, 0.6) + @test false == ceil(Bool, -0.7) + end +end