Skip to content

Commit 265d0af

Browse files
committed
Add support for specifying RoundingMode for round
1 parent 08d9ead commit 265d0af

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

src/FixedPointNumbers.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,15 @@ for f in (:+, :-, :rem, :mod, :mod1, :min, :max)
139139
$f(x::X, y::X) where {X <: FixedPoint} = X($f(x.i, y.i), 0)
140140
end
141141
end
142+
for (m, f) in ((:(:Nearest), :round),
143+
(:(:ToZero), :trunc),
144+
(:(:Up), :ceil),
145+
(:(:Down), :floor))
146+
@eval begin
147+
round(x::FixedPoint, ::RoundingMode{$m}) = $f(x)
148+
round(::Type{Ti}, x::FixedPoint, ::RoundingMode{$m}) where {Ti <: Integer} = $f(Ti, x)
149+
end
150+
end
142151

143152
# Printing. These are used to generate type-symbols, so we need them
144153
# before we include any files.

test/fixed.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,16 @@ end
144144
@test_throws ArgumentError round(typemax(F) - F(0.5) + eps(F))
145145
end
146146
end
147+
@testset "rounding mode" begin
148+
@test round(-1.5Q1f6, RoundNearest) === -2Q1f6
149+
@test round(-1.5Q1f6, RoundToZero) === -1Q1f6
150+
@test round(-1.5Q1f6, RoundUp) === -1Q1f6
151+
@test round(-1.5Q1f6, RoundDown) === -2Q1f6
152+
@test round(Int, -1.5Q1f6, RoundNearest) === -2
153+
@test round(Int, -1.5Q1f6, RoundToZero) === -1
154+
@test round(Int, -1.5Q1f6, RoundUp) === -1
155+
@test round(Int, -1.5Q1f6, RoundDown) === -2
156+
end
147157
@test_throws InexactError trunc(UInt, typemin(Q0f7))
148158
@test_throws InexactError floor(UInt, -eps(Q0f7))
149159
end

test/normed.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,16 @@ end
264264
@test_throws ArgumentError ceil(typemax(N))
265265
@test_throws ArgumentError ceil(floor(typemax(N)) + eps(N))
266266
end
267+
@testset "rounding mode" begin
268+
@test round(1.504N1f7, RoundNearest) === 2N1f7
269+
@test round(1.504N1f7, RoundToZero) === 1N1f7
270+
@test round(1.504N1f7, RoundUp) === 2N1f7
271+
@test round(1.504N1f7, RoundDown) === 1N1f7
272+
@test round(Int, 1.504N1f7, RoundNearest) === 2
273+
@test round(Int, 1.504N1f7, RoundToZero) === 1
274+
@test round(Int, 1.504N1f7, RoundUp) === 2
275+
@test round(Int, 1.504N1f7, RoundDown) === 1
276+
end
267277
end
268278

269279
@testset "approx" begin

0 commit comments

Comments
 (0)