Skip to content

Commit

Permalink
Printf: don't zero pad Inf or NaN (#53785)
Browse files Browse the repository at this point in the history
We currently have
```
julia> @sprintf("%07f", -Inf)
"-000Inf"

julia> @sprintf("%07f", NaN)
"0000NaN"
```

With this PR
```
julia> @sprintf("%07f", -Inf)
"   -Inf"

julia> @sprintf("%07f", NaN)
"    NaN"
```
which is the same as Julia 1.5.4 and agrees with the C standard.
  • Loading branch information
jmkuhn authored Mar 20, 2024
1 parent a30feec commit 55afecc
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
2 changes: 1 addition & 1 deletion stdlib/Printf/src/Printf.jl
Original file line number Diff line number Diff line change
Expand Up @@ -654,7 +654,7 @@ const __BIG_FLOAT_MAX__ = 8192
else
# right aligned
n = width - (newpos - pos)
if zero
if zero && isfinite(x)
ex = (arg < 0 || (plus | space)) + (T <: Union{Val{'a'}, Val{'A'}} ? 2 : 0)
so = pos + ex
len = (newpos - pos) - ex
Expand Down
6 changes: 6 additions & 0 deletions stdlib/Printf/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,15 @@ end
@test (Printf.@sprintf "%+f" Inf) == "+Inf"
@test (Printf.@sprintf "% f" Inf) == " Inf"
@test (Printf.@sprintf "% #f" Inf) == " Inf"
@test (Printf.@sprintf "%07f" Inf) == " Inf"
@test (Printf.@sprintf "%f" -Inf) == "-Inf"
@test (Printf.@sprintf "%+f" -Inf) == "-Inf"
@test (Printf.@sprintf "%07f" -Inf) == " -Inf"
@test (Printf.@sprintf "%f" NaN) == "NaN"
@test (Printf.@sprintf "%+f" NaN) == "+NaN"
@test (Printf.@sprintf "% f" NaN) == " NaN"
@test (Printf.@sprintf "% #f" NaN) == " NaN"
@test (Printf.@sprintf "%07f" NaN) == " NaN"
@test (Printf.@sprintf "%e" big"Inf") == "Inf"
@test (Printf.@sprintf "%e" big"NaN") == "NaN"

Expand Down Expand Up @@ -169,12 +172,15 @@ end
@test (Printf.@sprintf "%+e" Inf) == "+Inf"
@test (Printf.@sprintf "% e" Inf) == " Inf"
@test (Printf.@sprintf "% #e" Inf) == " Inf"
@test (Printf.@sprintf "%07e" Inf) == " Inf"
@test (Printf.@sprintf "%e" -Inf) == "-Inf"
@test (Printf.@sprintf "%+e" -Inf) == "-Inf"
@test (Printf.@sprintf "%07e" -Inf) == " -Inf"
@test (Printf.@sprintf "%e" NaN) == "NaN"
@test (Printf.@sprintf "%+e" NaN) == "+NaN"
@test (Printf.@sprintf "% e" NaN) == " NaN"
@test (Printf.@sprintf "% #e" NaN) == " NaN"
@test (Printf.@sprintf "%07e" NaN) == " NaN"
@test (Printf.@sprintf "%e" big"Inf") == "Inf"
@test (Printf.@sprintf "%e" big"NaN") == "NaN"

Expand Down

0 comments on commit 55afecc

Please sign in to comment.