Skip to content

Commit fe1264a

Browse files
authored
define round/trunc/ceil/floor to Bool (#25085)
1 parent a2e4226 commit fe1264a

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

base/float.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,12 @@ floor(::Type{T}, x::AbstractFloat) where {T<:Integer} = trunc(T,round(x, RoundDo
358358
ceil(::Type{T}, x::AbstractFloat) where {T<:Integer} = trunc(T,round(x, RoundUp))
359359
round(::Type{T}, x::AbstractFloat) where {T<:Integer} = trunc(T,round(x, RoundNearest))
360360

361+
# Bool
362+
trunc(::Type{Bool}, x::AbstractFloat) = (-1 < x < 2) ? 1 <= x : throw(InexactError(:trunc, Bool, x))
363+
floor(::Type{Bool}, x::AbstractFloat) = (0 <= x < 2) ? 1 <= x : throw(InexactError(:floor, Bool, x))
364+
ceil(::Type{Bool}, x::AbstractFloat) = (-1 < x <= 1) ? 0 < x : throw(InexactError(:ceil, Bool, x))
365+
round(::Type{Bool}, x::AbstractFloat) = (-0.5 <= x < 1.5) ? 0.5 < x : throw(InexactError(:round, Bool, x))
366+
361367
round(x::IEEEFloat, r::RoundingMode{:ToZero}) = trunc_llvm(x)
362368
round(x::IEEEFloat, r::RoundingMode{:Down}) = floor_llvm(x)
363369
round(x::IEEEFloat, r::RoundingMode{:Up}) = ceil_llvm(x)

test/numbers.jl

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2813,3 +2813,45 @@ end
28132813
@test_throws MethodError fld(a, b)
28142814
@test_throws MethodError cld(a, b)
28152815
end
2816+
2817+
@testset "Bool rounding (#25074)" begin
2818+
@testset "round Bool" begin
2819+
@test_throws InexactError round(Bool, -4.1)
2820+
@test_throws InexactError round(Bool, 1.5)
2821+
@test true == round(Bool, 1.0)
2822+
@test false == round(Bool, 0.0)
2823+
@test true == round(Bool, 0.6)
2824+
@test false == round(Bool, 0.4)
2825+
@test false == round(Bool, 0.5)
2826+
@test false == round(Bool, -0.5)
2827+
end
2828+
2829+
@testset "trunc Bool" begin
2830+
@test_throws InexactError trunc(Bool, -4.1)
2831+
@test_throws InexactError trunc(Bool, 2.5)
2832+
@test true == trunc(Bool, 1.0)
2833+
@test false == trunc(Bool, 0.0)
2834+
@test false == trunc(Bool, 0.6)
2835+
@test false == trunc(Bool, 0.4)
2836+
@test true == trunc(Bool, 1.8)
2837+
@test false == trunc(Bool, -0.5)
2838+
end
2839+
2840+
@testset "floor Bool" begin
2841+
@test_throws InexactError floor(Bool, -0.1)
2842+
@test_throws InexactError floor(Bool, 2.5)
2843+
@test true == floor(Bool, 1.0)
2844+
@test false == floor(Bool, 0.0)
2845+
@test false == floor(Bool, 0.6)
2846+
@test true == floor(Bool, 1.8)
2847+
end
2848+
2849+
@testset "ceil Bool" begin
2850+
@test_throws InexactError ceil(Bool, -1.4)
2851+
@test_throws InexactError ceil(Bool, 1.5)
2852+
@test true == ceil(Bool, 1.0)
2853+
@test false == ceil(Bool, 0.0)
2854+
@test true == ceil(Bool, 0.6)
2855+
@test false == ceil(Bool, -0.7)
2856+
end
2857+
end

0 commit comments

Comments
 (0)