Skip to content

Commit

Permalink
Fix coercion of floats to integer for %d printf specifier
Browse files Browse the repository at this point in the history
Fixes JuliaLang#37507. The issue here was the calling of `trunc` instead of
`round` when coercing `AbstractFloat` arguments to `Integer`. Note this
throws a scary warning and has undefined behavior in C, but it looks
like legacy Printf code supported this, so we can try to do the right
thing here. Previously, Printf called the grisu equivalent of
`Ryu.writefixed(x, precision=0)` for float arguments, but as far as I
can tell, calling `round(x)` should accomplish the same thing.
  • Loading branch information
quinnj committed Sep 10, 2020
1 parent c7b17fe commit 52d4527
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 2 deletions.
4 changes: 2 additions & 2 deletions stdlib/Printf/src/Printf.jl
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ end
leftalign, plus, space, zero, hash, width, prec =
spec.leftalign, spec.plus, spec.space, spec.zero, spec.hash, spec.width, spec.precision
bs = base(T)
arg2 = arg isa AbstractFloat ? Integer(trunc(arg)) : arg
arg2 = arg isa AbstractFloat ? Integer(round(arg)) : arg
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 @@ -675,7 +675,7 @@ function plength(f::Spec{T}, x) where {T <: Strings}
end

function plength(f::Spec{T}, x) where {T <: Ints}
x2 = x isa AbstractFloat ? Integer(trunc(x)) : x
x2 = x isa AbstractFloat ? Integer(round(x)) : x
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 @@ -423,6 +423,8 @@ end
@test_throws ArgumentError @sprintf("%s%%%s", "a")
@test @sprintf("%s%%%s", "a", "b") == "a%%b"

# print float as %d uses round(x)
@test @sprintf("%d", 25.5) == "26"
end

@testset "integers" begin
Expand Down

0 comments on commit 52d4527

Please sign in to comment.