Skip to content

Commit b9fcccc

Browse files
jmkuhnstevengj
authored andcommitted
Add trunc(x), floor(x), ceil(x) (#61)
* Add trunc(x), floor(x), ceil(x) * Use signbit
1 parent 652678c commit b9fcccc

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

src/DecFP.jl

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,10 +303,12 @@ for w in (32,64,128)
303303
@eval Base.$f(x::$BID) = @xchk(ccall(($(bidsym(w,f)), libbid), $BID, ($BID,), x), DomainError, x, mask=INVALID)
304304
end
305305

306-
for (f,c) in ((:gamma,"tgamma"), (:-,"negate"), (:round,"nearbyint"))
306+
for (f,c) in ((:gamma,"tgamma"), (:-,"negate"), (:trunc,"round_integral_zero"), (:floor,"round_integral_negative"), (:ceil,"round_integral_positive"), (:round,"nearbyint"))
307307
@eval Base.$f(x::$BID) = @xchk(ccall(($(bidsym(w,c)), libbid), $BID, ($BID,), x), DomainError, x, mask=INVALID)
308308
end
309309

310+
@eval Base.round(x::$BID, ::RoundingMode{:Nearest}) = @xchk(ccall(($(bidsym(w,"round_integral_nearest_even")), libbid), $BID, ($BID,), x), DomainError, x, mask=INVALID)
311+
310312
for (f,c) in ((:(==),"quiet_equal"), (:>,"quiet_greater"), (:<,"quiet_less"), (:(>=), "quiet_greater_equal"), (:(<=), "quiet_less_equal"))
311313
@eval Base.$f(x::$BID, y::$BID) = nox(ccall(($(bidsym(w,c)), libbid), Cint, ($BID,$BID), x, y) != 0)
312314
end
@@ -374,6 +376,8 @@ for w in (32,64,128)
374376
@eval Base.reinterpret(::Type{$Ti}, x::$BID) = x.x
375377
end # widths w
376378

379+
Base.round(x::DecimalFloatingPoint, ::RoundingMode{:FromZero}) = signbit(x) ? floor(x) : ceil(x)
380+
377381
Base.trunc(::Type{Integer}, x::DecimalFloatingPoint) = trunc(Int, x)
378382
Base.floor(::Type{Integer}, x::DecimalFloatingPoint) = floor(Int, x)
379383
Base.ceil(::Type{Integer}, x::DecimalFloatingPoint) = ceil(Int, x)

test/runtests.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,13 @@ for T in (Dec32, Dec64, Dec128)
153153
for Tf in (Float64, Float32, Float16)
154154
@test xd == Tf(x) == T(Tf(x)) == Tf(xd)
155155
end
156+
157+
@test trunc(T(2.7)) === floor(T(2.7)) === round(T(2.7), RoundDown) === round(T(2.7), RoundToZero) === T(2)
158+
@test ceil(T(2.3)) === round(T(2.3), RoundUp) === round(T(2.3), RoundFromZero) === T(3)
159+
@test round(T(1.5)) === round(T(2.5)) === round(T(1.5), RoundNearest) === round(T(2.5), RoundNearest) === T(2)
160+
@test round(T(2.5), RoundNearestTiesAway) === round(T(3.3), RoundNearestTiesAway) === T(3)
161+
@test round(T(2.5), RoundNearestTiesUp) === round(T(3.3), RoundNearestTiesUp) === T(3)
162+
156163
for Ti in (Integer,Int8,UInt8,Int16,UInt16,Int32,UInt32,Int64,UInt64)
157164
if Ti != Integer
158165
@test parse(T, "17") == T(Ti(17)) == Ti(17) == Ti(T(17))

0 commit comments

Comments
 (0)