Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

skip show when denominator is one #45396

Merged
merged 11 commits into from
Mar 9, 2023
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 5 additions & 0 deletions base/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions test/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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{Int64}[-1]"
@test sprint(show, MIME"text/plain"(), Union{Int, Rational{Int}}[7 3//6; 6//3 2]) ==
"2×2 Matrix{Union{Rational{Int64}, Int64}}:\n 7 1//2\n 2//1 2"
kalmarek marked this conversation as resolved.
Show resolved Hide resolved
let
io1 = IOBuffer()
write(io1, rational1)
Expand Down