From 897e33ccc431e6d613ffa6c5f006cfbbb3fb83f9 Mon Sep 17 00:00:00 2001 From: Gavin Hayes Date: Thu, 18 Aug 2022 18:53:07 -0400 Subject: [PATCH] Fix stdio fmt of "%.0e" and "%.0g" (#544) * Fix %.0e by always rounding even if precision is 0 * Fix %.0g by treating it the same as %.1g * Fix %g tests to match glibc, add more tests --- libc/stdio/dtoa.c | 6 +++--- test/libc/fmt/fmt_test.c | 16 ++++++++++++++-- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/libc/stdio/dtoa.c b/libc/stdio/dtoa.c index f0c7ee86e..7622f2561 100644 --- a/libc/stdio/dtoa.c +++ b/libc/stdio/dtoa.c @@ -335,10 +335,10 @@ int __fmt_dtoa(int (*out)(const char *, void *, size_t), void *arg, int d, case 'G': case 'g': if (!(flags & FLAGS_PRECISION)) prec = 6; - if (prec < 0) prec = 0; + if (prec < 1) prec = 1; if (!longdouble) { x = va_arg(va, double); - s = s0 = dtoa(x, prec ? 2 : 0, prec, &decpt, &fpb.sign, &se); + s = s0 = dtoa(x, 2, prec, &decpt, &fpb.sign, &se); if (decpt == 9999) { if (s && s[0] == 'N') { fpb.kind = STRTOG_NaN; @@ -379,7 +379,7 @@ int __fmt_dtoa(int (*out)(const char *, void *, size_t), void *arg, int d, if (prec < 0) prec = 0; if (!longdouble) { x = va_arg(va, double); - s = s0 = dtoa(x, prec ? 2 : 0, prec + 1, &decpt, &fpb.sign, &se); + s = s0 = dtoa(x, 2, prec + 1, &decpt, &fpb.sign, &se); if (decpt == 9999) { if (s && s[0] == 'N') { fpb.kind = STRTOG_NaN; diff --git a/test/libc/fmt/fmt_test.c b/test/libc/fmt/fmt_test.c index b0052879d..e1670084a 100644 --- a/test/libc/fmt/fmt_test.c +++ b/test/libc/fmt/fmt_test.c @@ -70,12 +70,24 @@ TEST(fmt, g) { EXPECT_STREQ("+1", gc(xasprintf("%+g", 1.))); EXPECT_STREQ("-1", gc(xasprintf("%g", -1.))); EXPECT_STREQ("10", gc(xasprintf("%g", 10.))); - EXPECT_STREQ("10", gc(xasprintf("%.0g", 10.))); EXPECT_STREQ("-10", gc(xasprintf("%g", -10.))); - EXPECT_STREQ("-10", gc(xasprintf("%.0g", -10.))); + EXPECT_STREQ("1e+01", gc(xasprintf("%.0g", 10.))); + EXPECT_STREQ("-1e+01", gc(xasprintf("%.0g", -10.))); + EXPECT_STREQ("1", gc(xasprintf("%.0g", 1.0))); + EXPECT_STREQ("1e-05", gc(xasprintf("%.0g", 0.00001))); + EXPECT_STREQ("0.0001", gc(xasprintf("%.0g", 0.0001))); + EXPECT_STREQ("1e+01", gc(xasprintf("%.1g", 10.))); + EXPECT_STREQ("-1e+01", gc(xasprintf("%.1g", -10.))); + EXPECT_STREQ("1", gc(xasprintf("%.1g", 1.0))); + EXPECT_STREQ("1e-05", gc(xasprintf("%.1g", 0.00001))); + EXPECT_STREQ("0.0001", gc(xasprintf("%.1g", 0.0001))); + EXPECT_STREQ("0.007812", gc(xasprintf("%.4g", 0.0078125))); + EXPECT_STREQ("0.023438", gc(xasprintf("%.5g", 0.0234375))); EXPECT_STREQ("1e+100", gc(xasprintf("%g", 1e100))); EXPECT_STREQ("1e-100", gc(xasprintf("%g", 1e-100))); EXPECT_STREQ("-1e-100", gc(xasprintf("%g", -1e-100))); + EXPECT_STREQ("0.123456", gc(xasprintf("%g", 0.1234564))); + EXPECT_STREQ("0.123457", gc(xasprintf("%g", 0.1234566))); EXPECT_STREQ("3.14159", gc(xasprintf("%g", 0x1.921fb54442d1846ap+1))); EXPECT_STREQ("0", gc(xasprintf("%g", 0.))); EXPECT_STREQ("-0", gc(xasprintf("%g", -0.)));