diff --git a/base/floatfuncs.jl b/base/floatfuncs.jl index 7a15934ed58a3..85db2a2ae92e3 100644 --- a/base/floatfuncs.jl +++ b/base/floatfuncs.jl @@ -170,17 +170,17 @@ function _round(x, r::RoundingMode, digits::Integer, sigdigits::Nothing, base) end hidigit(x::Integer, base) = ndigits0z(x, base) -function hidigit(x::Real, base) +function hidigit(x::AbstractFloat, base) iszero(x) && return 0 - fx = float(x) if base == 10 - return 1 + floor(Int, log10(abs(fx))) + return 1 + floor(Int, log10(abs(x))) elseif base == 2 return 1 + exponent(x) else - return 1 + floor(Int, log(base, abs(fx))) + return 1 + floor(Int, log(base, abs(x))) end end +hidigit(x::Real, base) = hidigit(float(x), base) function _round(x, r::RoundingMode, digits::Nothing, sigdigits::Integer, base) h = hidigit(x, base) diff --git a/base/irrationals.jl b/base/irrationals.jl index 5f23988f5195b..5b4ab8351996c 100644 --- a/base/irrationals.jl +++ b/base/irrationals.jl @@ -125,6 +125,8 @@ for op in Symbol[:+, :-, :*, :/, :^] end *(x::Bool, y::AbstractIrrational) = ifelse(x, Float64(y), 0.0) +_round(x::Irrational, r::RoundingMode) = _round(float(x), r) + macro irrational(sym, val, def) esym = esc(sym) qsym = esc(Expr(:quote, sym)) diff --git a/test/rounding.jl b/test/rounding.jl index c7b0c9dde2864..a9c183228b5b8 100644 --- a/test/rounding.jl +++ b/test/rounding.jl @@ -265,8 +265,13 @@ end # custom rounding and significant-digit ops @testset "rounding to digits relative to the decimal point" begin + @test round(pi) ≈ 3. @test round(pi, digits=0) ≈ 3. @test round(pi, digits=1) ≈ 3.1 + @test round(pi, digits=3, base=2) ≈ 3.125 + @test round(pi, sigdigits=1) ≈ 3. + @test round(pi, sigdigits=3) ≈ 3.14 + @test round(pi, sigdigits=4, base=2) ≈ 3.25 @test round(10*pi, digits=-1) ≈ 30. @test round(.1, digits=0) == 0. @test round(-.1, digits=0) == -0.