Skip to content

Commit

Permalink
Merge pull request JuliaLang#37570 from JuliaLang/jq/37552
Browse files Browse the repository at this point in the history
Treat Inf/NaN specially for %d formatting
  • Loading branch information
quinnj committed Sep 14, 2020
2 parents 4c805d2 + 3e13b0c commit 4e07a39
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
10 changes: 9 additions & 1 deletion stdlib/Printf/src/Printf.jl
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ Base.string(f::Spec{T}; modifier::String="") where {T} =
f.precision == 0 ? ".0" : f.precision > 0 ? ".$(f.precision)" : "", modifier, char(T))
Base.show(io::IO, f::Spec) = print(io, string(f))

nonfinitefmt(s::Spec{T}) where {T} =
Spec{Val{'g'}}(s.leftalign, s.plus, s.space, s.zero, s.hash, s.width, s.precision)
ptrfmt(s::Spec{T}, x) where {T} =
Spec{Val{'x'}}(s.leftalign, s.plus, s.space, s.zero, true, s.width, sizeof(x) == 8 ? 16 : 8)

Expand Down Expand Up @@ -264,7 +266,7 @@ end
# integers
toint(x) = x
toint(x::Rational) = Integer(x)
toint(x::AbstractFloat) = x > typemax(Int128) ?
toint(x::AbstractFloat) = !isfinite(x) ? x : x > typemax(Int128) ?
BigInt(round(x)) : x > typemax(Int64) ?
Int128(round(x)) : Int64(round(x))

Expand All @@ -273,6 +275,9 @@ toint(x::AbstractFloat) = x > typemax(Int128) ?
spec.leftalign, spec.plus, spec.space, spec.zero, spec.hash, spec.width, spec.precision
bs = base(T)
arg2 = toint(arg)
if !isfinite(arg2)
return fmt(buf, pos, arg, nonfinitefmt(spec))
end
n = i = ndigits(arg2, base=bs, pad=1)
x, neg = arg2 < 0 ? (-arg2, true) : (arg2, false)
arglen = n + (neg || (plus | space)) +
Expand Down Expand Up @@ -682,6 +687,9 @@ end

function plength(f::Spec{T}, x) where {T <: Ints}
x2 = toint(x)
if !isfinite(x2)
return plength(nonfinitefmt(f), x)
end
return max(f.width, f.precision + ndigits(x2, base=base(T), pad=1) + 5)
end

Expand Down
2 changes: 2 additions & 0 deletions stdlib/Printf/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,8 @@ end
# 37552
@test @sprintf("%d", 1.0e100) == "10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104"
@test @sprintf("%d", 3//1) == "3"
@test @sprintf("%d", Inf) == "Inf"
@test @sprintf(" %d", NaN) == " NaN"
end

@testset "integers" begin
Expand Down

0 comments on commit 4e07a39

Please sign in to comment.