Skip to content

Commit bc12eca

Browse files
committed
py/formatfloat: Fix rounding of %f format with edge-case FP values.
Prior to this patch the %f formatting of some FP values could be off by up to 1, eg '%.0f' % 123 would return "122" (unix x64). Depending on the FP precision (single vs double) certain numbers would format correctly, but others wolud not. This patch should fix all cases of rounding for %f.
1 parent 90e719a commit bc12eca

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

py/formatfloat.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch
341341
// Round
342342
// If we print non-exponential format (i.e. 'f'), but a digit we're going
343343
// to round by (e) is too far away, then there's nothing to round.
344-
if ((org_fmt != 'f' || e <= 1) && f >= FPCONST(5.0)) {
344+
if ((org_fmt != 'f' || e <= num_digits) && f >= FPCONST(5.0)) {
345345
char *rs = s;
346346
rs--;
347347
while (1) {

tests/float/float_format.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# test float formatting
2+
3+
# general rounding
4+
for val in (116, 1111, 1234, 5010, 11111):
5+
print('%.0f' % val)
6+
print('%.1f' % val)
7+
print('%.3f' % val)
8+
9+
# make sure rounding is done at the correct precision
10+
for prec in range(8):
11+
print(('%%.%df' % prec) % 6e-5)

tests/unix/extra_coverage.py.exp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ Warning: test
5656
+1e+00
5757
+1e+00
5858
# binary
59-
122
59+
123
6060
456
6161
# VM
6262
2 1

0 commit comments

Comments
 (0)