Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constructors with RoundingMode #118

Merged
merged 1 commit into from
May 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/DecFP.jl
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,13 @@ for w in (32,64,128)
$BID(x::Number) = convert($BID, x)
Base.reinterpret(::Type{$BID}, x::$Ti) = new(x)
end

@eval function $BID(x::Real, mode::RoundingMode)
setrounding($BID, mode) do
convert($BID, x)
end
end

# fix method ambiguities:
@eval $BID(x::Rational{T}) where {T} = convert($BID, x)
end
Expand Down Expand Up @@ -209,6 +216,12 @@ for w in (32,64,128)

$BID(x::AbstractString) = parse($BID, x)

function $BID(x::AbstractString, mode::RoundingMode)
setrounding($BID, mode) do
parse($BID, x)
end
end

function tostring(x::$BID)
# fills global _buffer
ccall(($(bidsym(w,"to_string")), libbid), Cvoid, (Ptr{UInt8},$BID,Ref{Cuint}), _buffer[Threads.threadid()], x, RefArray(flags, Threads.threadid()))
Expand Down
17 changes: 17 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,23 @@ for T in (Dec32, Dec64, Dec128)
@test parse(T, "0.1")::T == T(1//10)
@test T("0.1")::T == T(1//10)

if T != Dec128
@test T(0.1) == T("0.1")
@test T(0.1, RoundNearest) == T("0.1")
@test T(0.1, RoundDown) == T("0.1")
@test T(0.1, RoundUp) == nextfloat(T("0.1"))
end
@test T("1", RoundDown) == T(1)
@test T("1", RoundUp) == T(1)
@test T("1.0000000000000000000000000000000000000001") == T(1)
@test T("1.0000000000000000000000000000000000000001", RoundNearest) == T(1)
@test T("1.0000000000000000000000000000000000000001", RoundDown) == T(1)
@test T("1.0000000000000000000000000000000000000001", RoundUp) == nextfloat(T(1))
@test T("0.9999999999999999999999999999999999999999") == T(1)
@test T("0.9999999999999999999999999999999999999999", RoundNearest) == T(1)
@test T("0.9999999999999999999999999999999999999999", RoundUp) == T(1)
@test T("0.9999999999999999999999999999999999999999", RoundDown) == prevfloat(T(1))

io = IOBuffer()
show(io, T("NaN")); @test String(take!(io)) == "NaN"
show(io, T("Inf")); @test String(take!(io)) == "Inf"
Expand Down