Skip to content

Commit 691cf74

Browse files
authored
Merge pull request #40496 from bicycle1885/fix-printf-a
fix %a/%A format for zeros
2 parents b673576 + 17ede14 commit 691cf74

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed

stdlib/Printf/src/Printf.jl

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,7 @@ const __BIG_FLOAT_MAX__ = 8192
425425
x = round(x, sigdigits=prec)
426426
newpos = Ryu.writeshortest(buf, pos, x, plus, space, hash, prec, T == Val{'g'} ? UInt8('e') : UInt8('E'), true, UInt8('.'))
427427
elseif T == Val{'a'} || T == Val{'A'}
428-
x, neg = x < 0 ? (-x, true) : (x, false)
428+
x, neg = x < 0 || x === -Base.zero(x) ? (-x, true) : (x, false)
429429
newpos = pos
430430
if neg
431431
buf[newpos] = UInt8('-')
@@ -456,6 +456,8 @@ const __BIG_FLOAT_MAX__ = 8192
456456
buf[newpos] = UInt8('0')
457457
newpos += 1
458458
if prec > 0
459+
buf[newpos] = UInt8('.')
460+
newpos += 1
459461
while prec > 0
460462
buf[newpos] = UInt8('0')
461463
newpos += 1
@@ -465,6 +467,7 @@ const __BIG_FLOAT_MAX__ = 8192
465467
buf[newpos] = T <: Val{'a'} ? UInt8('p') : UInt8('P')
466468
buf[newpos + 1] = UInt8('+')
467469
buf[newpos + 2] = UInt8('0')
470+
newpos += 3
468471
else
469472
if prec > -1
470473
s, p = frexp(x)

stdlib/Printf/test/runtests.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ end
2727
@testset "%a" begin
2828

2929
# hex float
30+
@test (Printf.@sprintf "%a" 0.0) == "0x0p+0"
31+
@test (Printf.@sprintf "%a" -0.0) == "-0x0p+0"
32+
@test (Printf.@sprintf "%.3a" 0.0) == "0x0.000p+0"
3033
@test (Printf.@sprintf "%a" 1.5) == "0x1.8p+0"
3134
@test (Printf.@sprintf "%a" 1.5f0) == "0x1.8p+0"
3235
@test (Printf.@sprintf "%a" big"1.5") == "0x1.8p+0"

0 commit comments

Comments
 (0)