From fbe1088314b8202688849f4d8002d8d2dc63a0da Mon Sep 17 00:00:00 2001 From: Kenta Sato Date: Mon, 3 May 2021 15:20:37 +0900 Subject: [PATCH] make Printf's general format C11 compliant --- stdlib/Printf/src/Printf.jl | 23 +++++++++++++++++++++-- stdlib/Printf/test/runtests.jl | 8 ++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/stdlib/Printf/src/Printf.jl b/stdlib/Printf/src/Printf.jl index f77fa89aa1fe58..b40ce3406f2124 100644 --- a/stdlib/Printf/src/Printf.jl +++ b/stdlib/Printf/src/Printf.jl @@ -421,9 +421,28 @@ const __BIG_FLOAT_MAX__ = 8192 elseif T == Val{'f'} || T == Val{'F'} newpos = Ryu.writefixed(buf, pos, x, prec, plus, space, hash, UInt8('.')) elseif T == Val{'g'} || T == Val{'G'} + # C11-compliant general format prec = prec == 0 ? 1 : prec - x = round(x, sigdigits=prec) - newpos = Ryu.writeshortest(buf, pos, x, plus, space, hash, prec, T == Val{'g'} ? UInt8('e') : UInt8('E'), true, UInt8('.')) + # format the value in scientific notation and parse the exponent part + exp = let p = Ryu.writeexp(buf, pos, x, prec) + b1, b2, b3, b4 = buf[p-4], buf[p-3], buf[p-2], buf[p-1] + Z = UInt8('0') + if b1 == UInt8('e') + # two-digit exponent + sign = b2 == UInt8('+') ? 1 : -1 + exp = 10 * (b3 - Z) + (b4 - Z) + else + # three-digit exponent + sign = b1 == UInt8('+') ? 1 : -1 + exp = 100 * (b2 - Z) + 10 * (b3 - Z) + (b4 - Z) + end + flipsign(exp, sign) + end + if -4 ≤ exp < prec + newpos = Ryu.writefixed(buf, pos, x, prec - (exp + 1), plus, space, hash, UInt8('.'), !hash) + else + newpos = Ryu.writeexp(buf, pos, x, prec - 1, plus, space, hash, T == Val{'g'} ? UInt8('e') : UInt8('E'), UInt8('.'), !hash) + end elseif T == Val{'a'} || T == Val{'A'} x, neg = x < 0 || x === -Base.zero(x) ? (-x, true) : (x, false) newpos = pos diff --git a/stdlib/Printf/test/runtests.jl b/stdlib/Printf/test/runtests.jl index 1dcd30d0971f15..212a74da2b4c61 100644 --- a/stdlib/Printf/test/runtests.jl +++ b/stdlib/Printf/test/runtests.jl @@ -449,6 +449,14 @@ end @test Printf.@sprintf("%e", 1) == "1.000000e+00" @test Printf.@sprintf("%g", 1) == "1" + # issue #39748 + @test Printf.@sprintf("%.16g", 194.4778127560983) == "194.4778127560983" + @test Printf.@sprintf("%.17g", 194.4778127560983) == "194.4778127560983" + @test Printf.@sprintf("%.18g", 194.4778127560983) == "194.477812756098302" + @test Printf.@sprintf("%.1g", 1.7976931348623157e308) == "2e+308" + @test Printf.@sprintf("%.2g", 1.7976931348623157e308) == "1.8e+308" + @test Printf.@sprintf("%.3g", 1.7976931348623157e308) == "1.8e+308" + # escaped '%' @test_throws ArgumentError @sprintf("%s%%%s", "a") @test @sprintf("%s%%%s", "a", "b") == "a%b"