diff --git a/py/formatfloat.c b/py/formatfloat.c index 9ff80d9f63..b16746b39b 100644 --- a/py/formatfloat.c +++ b/py/formatfloat.c @@ -376,11 +376,16 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch rs[1] = '0'; if (e_sign == '-') { e--; + if (e == 0) { + e_sign = '+'; + } } else { e++; } + } else { + // Need at extra digit at the end to make room for the leading '1' + s++; } - s++; char *ss = s; while (ss > rs) { *ss = ss[-1]; diff --git a/tests/float/string_format_modulo.py b/tests/float/string_format_modulo.py index 03c8dd00aa..aea534247c 100644 --- a/tests/float/string_format_modulo.py +++ b/tests/float/string_format_modulo.py @@ -44,3 +44,6 @@ print(('%.40g' % 1e-3)[:2]) print(('%.40g' % 1e-4)[:2]) print("%.0g" % 1) # 0 precision 'g' + +print('%.1e' % 9.99) # round up with positive exponent +print('%.1e' % 0.999) # round up with negative exponent diff --git a/tests/float/string_format_modulo3.py b/tests/float/string_format_modulo3.py index 5639647865..5d26f25751 100644 --- a/tests/float/string_format_modulo3.py +++ b/tests/float/string_format_modulo3.py @@ -1,4 +1,3 @@ # uPy and CPython outputs differ for the following print("%.1g" % -9.9) # round up 'g' with '-' sign -print("%.1e" % 9.99) # round up with positive exponent -print("%.1e" % 0.999) # round up with negative exponent +print("%.2g" % 99.9) # round up diff --git a/tests/float/string_format_modulo3.py.exp b/tests/float/string_format_modulo3.py.exp index b158c7d7f3..71432b3404 100644 --- a/tests/float/string_format_modulo3.py.exp +++ b/tests/float/string_format_modulo3.py.exp @@ -1,3 +1,2 @@ -10 -1.00e+01 -1.00e-00 +100