Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

two/three-argument round, ceil, floor, trunk, signif

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...
commit 4c88c229955be98b79c2d084e105434f0577b936 1 parent 9e4e894
@HarlanH HarlanH authored StefanKarpinski committed
Showing with 36 additions and 0 deletions.
  1. +1 −0  base/export.jl
  2. +35 −0 base/floatfuncs.jl
View
1  base/export.jl
@@ -473,6 +473,7 @@ export
sign,
signbit,
signed,
+ signif,
significand,
sin,
sinc,
View
35 base/floatfuncs.jl
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.