diff --git a/NEWS.md b/NEWS.md index 91b47d832eb29..2fb5e6a687550 100644 --- a/NEWS.md +++ b/NEWS.md @@ -40,6 +40,7 @@ Standard library changes ------------------------ * `startswith` now supports seekable `IO` streams ([#43055]) +* printing integral `Rational`s will skip the denominator in `Rational`-typed IO context (e.g. in `Arrays`) ([#45396]) #### Package Manager diff --git a/base/rational.jl b/base/rational.jl index 26746ad0b4bc2..3cfb038ab3b38 100644 --- a/base/rational.jl +++ b/base/rational.jl @@ -83,6 +83,11 @@ end function show(io::IO, x::Rational) show(io, numerator(x)) + + if isone(denominator(x)) && get(io, :typeinfo, Any) <: Rational + return + end + print(io, "//") show(io, denominator(x)) end diff --git a/test/rational.jl b/test/rational.jl index 9f47f2cb9dd16..a0833d08eb218 100644 --- a/test/rational.jl +++ b/test/rational.jl @@ -253,6 +253,10 @@ end rational2 = Rational(-4500, 9000) @test sprint(show, rational1) == "1465//8593" @test sprint(show, rational2) == "-1//2" + @test sprint(show, -2//2) == "-1//1" + @test sprint(show, [-2//2,]) == "Rational{$Int}[-1]" + @test sprint(show, MIME"text/plain"(), Union{Int, Rational{Int}}[7 3//6; 6//3 2]) == + "2×2 Matrix{Union{Rational{$Int}, $Int}}:\n 7 1//2\n 2//1 2" let io1 = IOBuffer() write(io1, rational1)