Skip to content

Commit

Permalink
two/three-argument round, ceil, floor, trunk, signif
Browse files Browse the repository at this point in the history
Some two-argument examples:

    julia> round(123.456, 1)
    100.0

    julia> round(123.456, 2)
    120.0

    julia> round(123.456, 3)
    123.0

    julia> round(123.456, 7)
    123.456

    julia> round(123.456, 4)
    123.5

    julia> round(-123.456, 4)
    -123.5

    julia> floor(123.456, 4)
    123.4

    julia> floor(-123.456, 4)
    -123.5

    julia> ceil(123.456, 4)
    123.5

    julia> ceil(-123.456, 4)
    -123.4

    julia> trunc(123.456, 4)
    123.4

    julia> trunc(-123.456, 4)
    -123.4
  • Loading branch information
HarlanH authored and StefanKarpinski committed Sep 12, 2012
1 parent 9e4e894 commit 4c88c22
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions base/export.jl
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,7 @@ export
sign,
signbit,
signed,
signif,
significand,
sin,
sinc,
Expand Down
35 changes: 35 additions & 0 deletions base/floatfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,38 @@ end
@vectorize_1arg Real isnan
@vectorize_1arg Real isinf
@vectorize_1arg Real isfinite

# adapted from Matlab File Exchange roundsd: http://www.mathworks.com/matlabcentral/fileexchange/26212
# for round, og is the power of 10 relative to the decimal point
# for signif, og is the absolute power of 10
# digits and base must be integers, x must be convertable to float

function _signif_og(x, digits, base)
if base == 10
10. ^ floor(log10(abs(x)) - digits + 1.)
elseif base == 2
2. ^ floor(log2(abs(x)) - digits + 1.)
else
float(base) ^ floor(log2(abs(x))/log2(base) - digits + 1.)
end
end
_round_og(digits, base) = float(base) ^ (- digits)

function signif(x, digits::Integer, base::Integer)
if digits < 0
throw(DomainError())
end
og = _signif_og(float(x), digits, base)
round(float(x)/og) * og
end
signif(x, digits) = signif(x, digits, 10)

for f in (:round, :ceil, :floor, :trunc)
@eval begin
function ($f)(x, digits::Integer, base::Integer)
og = _round_og(digits, base)
($f)(float(x) / og) * og
end
($f)(x, digits) = ($f)(x, digits, 10)
end
end

0 comments on commit 4c88c22

Please sign in to comment.