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.
This commit is contained in:
parent
90e719a232
commit
bc12eca461
|
@ -341,7 +341,7 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch
|
||||||
// Round
|
// Round
|
||||||
// If we print non-exponential format (i.e. 'f'), but a digit we're going
|
// If we print non-exponential format (i.e. 'f'), but a digit we're going
|
||||||
// to round by (e) is too far away, then there's nothing to round.
|
// to round by (e) is too far away, then there's nothing to round.
|
||||||
if ((org_fmt != 'f' || e <= 1) && f >= FPCONST(5.0)) {
|
if ((org_fmt != 'f' || e <= num_digits) && f >= FPCONST(5.0)) {
|
||||||
char *rs = s;
|
char *rs = s;
|
||||||
rs--;
|
rs--;
|
||||||
while (1) {
|
while (1) {
|
||||||
|
|
|
@ -0,0 +1,11 @@
|
||||||
|
# test float formatting
|
||||||
|
|
||||||
|
# general rounding
|
||||||
|
for val in (116, 1111, 1234, 5010, 11111):
|
||||||
|
print('%.0f' % val)
|
||||||
|
print('%.1f' % val)
|
||||||
|
print('%.3f' % val)
|
||||||
|
|
||||||
|
# make sure rounding is done at the correct precision
|
||||||
|
for prec in range(8):
|
||||||
|
print(('%%.%df' % prec) % 6e-5)
|
|
@ -56,7 +56,7 @@ Warning: test
|
||||||
+1e+00
|
+1e+00
|
||||||
+1e+00
|
+1e+00
|
||||||
# binary
|
# binary
|
||||||
122
|
123
|
||||||
456
|
456
|
||||||
# VM
|
# VM
|
||||||
2 1
|
2 1
|
||||||
|
|
Loading…
Reference in New Issue