Skip to content

Commit 6ed4581

Browse files
committed
py/formatfloat: Fix number of digits and exponent sign when rounding.
This patch fixes 2 things when printing a floating-point number that requires rounding up of the mantissa: - retain the correct precision; eg 0.99 becomes 1.0, not 1.00 - if the exponent goes from -1 to 0 then render it as +0, not -0
1 parent d42b80f commit 6ed4581

File tree

4 files changed

+11
-5
lines changed

4 files changed

+11
-5
lines changed

py/formatfloat.c

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -376,11 +376,16 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch
376376
rs[1] = '0';
377377
if (e_sign == '-') {
378378
e--;
379+
if (e == 0) {
380+
e_sign = '+';
381+
}
379382
} else {
380383
e++;
381384
}
385+
} else {
386+
// Need at extra digit at the end to make room for the leading '1'
387+
s++;
382388
}
383-
s++;
384389
char *ss = s;
385390
while (ss > rs) {
386391
*ss = ss[-1];

tests/float/string_format_modulo.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,6 @@
4444
print(('%.40g' % 1e-4)[:2])
4545

4646
print("%.0g" % 1) # 0 precision 'g'
47+
48+
print('%.1e' % 9.99) # round up with positive exponent
49+
print('%.1e' % 0.999) # round up with negative exponent

tests/float/string_format_modulo3.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
# uPy and CPython outputs differ for the following
22
print("%.1g" % -9.9) # round up 'g' with '-' sign
3-
print("%.1e" % 9.99) # round up with positive exponent
4-
print("%.1e" % 0.999) # round up with negative exponent
3+
print("%.2g" % 99.9) # round up
Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
-10
2-
1.00e+01
3-
1.00e-00
2+
100

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy