Skip to content
New issue

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

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

Already on GitHub? # to your account

Added trunc as another function for rounding #41

Merged
merged 3 commits into from
Sep 13, 2019
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
2 changes: 1 addition & 1 deletion src/Decimals.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# @author jack@tinybike.net (Jack Peterson), 7/3/2014

module Decimals
import Base: ==, +, -, *, /, <, float, inv, round
import Base: ==, +, -, *, /, <, float, inv, round, trunc

export Decimal,
decimal,
Expand Down
11 changes: 11 additions & 0 deletions src/round.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,14 @@ function round(x::Decimal; digits::Int=0, normal::Bool=false)
(normal) ? d : normalize(d, rounded=true)
end
end

function trunc(x::Decimal; digits::Int=0, normal::Bool=false)
shift = BigInt(digits) + x.q
if shift > BigInt(0) || shift < x.q
(normal) ? x : normalize(x, rounded=true)
else
c = Base.trunc(x.c / BigInt(10)^(-shift))
d = Decimal(x.s, BigInt(c), x.q - shift)
(normal) ? d : normalize(d, rounded=true)
end
end
3 changes: 3 additions & 0 deletions test/test_round.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ using Test

@test round.(Decimal.([0.1111, 0.2222, 0.8888]), digits=2) == Decimal.([0.11, 0.22, 0.89])

@test trunc(Decimal(7.123456), digits=5) == Decimal(7.12345)


function tet()
a = parse(Decimal, "1.0000001")
for i = 1:27
Expand Down