Skip to content

Commit 3e13b0c

Browse files
committed
Treat Inf/NaN specially for %d formatting
1 parent 4c805d2 commit 3e13b0c

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

stdlib/Printf/src/Printf.jl

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ Base.string(f::Spec{T}; modifier::String="") where {T} =
3838
f.precision == 0 ? ".0" : f.precision > 0 ? ".$(f.precision)" : "", modifier, char(T))
3939
Base.show(io::IO, f::Spec) = print(io, string(f))
4040

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

@@ -264,7 +266,7 @@ end
264266
# integers
265267
toint(x) = x
266268
toint(x::Rational) = Integer(x)
267-
toint(x::AbstractFloat) = x > typemax(Int128) ?
269+
toint(x::AbstractFloat) = !isfinite(x) ? x : x > typemax(Int128) ?
268270
BigInt(round(x)) : x > typemax(Int64) ?
269271
Int128(round(x)) : Int64(round(x))
270272

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

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

stdlib/Printf/test/runtests.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,8 @@ end
433433
# 37552
434434
@test @sprintf("%d", 1.0e100) == "10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104"
435435
@test @sprintf("%d", 3//1) == "3"
436+
@test @sprintf("%d", Inf) == "Inf"
437+
@test @sprintf(" %d", NaN) == " NaN"
436438
end
437439

438440
@testset "integers" begin

0 commit comments

Comments
 (0)