From 955ee6477f4b1d3a70bfe97a1e7727848bf2d06d Mon Sep 17 00:00:00 2001 From: Damien George Date: Thu, 1 Mar 2018 17:00:02 +1100 Subject: [PATCH] py/formatfloat: Fix case where floats could render with negative digits. Prior to this patch, some architectures (eg unix x86) could render floats with "negative" digits, like ")". For example, '%.23e' % 1e-80 would come out as "1.0000000000000000/)/(,*0e-80". This patch fixes the known cases. --- py/formatfloat.c | 6 +++++- tests/float/float_format.py | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/py/formatfloat.c b/py/formatfloat.c index 60dcee6f54..dc7fc1d1fd 100644 --- a/py/formatfloat.c +++ b/py/formatfloat.c @@ -330,7 +330,11 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch // Print the digits of the mantissa for (int i = 0; i < num_digits; ++i, --dec) { int32_t d = (int32_t)f; - *s++ = '0' + d; + if (d < 0) { + *s++ = '0'; + } else { + *s++ = '0' + d; + } if (dec == 0 && prec > 0) { *s++ = '.'; } diff --git a/tests/float/float_format.py b/tests/float/float_format.py index cda395ce02..d43535cf2f 100644 --- a/tests/float/float_format.py +++ b/tests/float/float_format.py @@ -13,3 +13,7 @@ for prec in range(8): # check certain cases that had a digit value of 10 render as a ":" character print('%.2e' % float('9' * 51 + 'e-39')) print('%.2e' % float('9' * 40 + 'e-21')) + +# check a case that would render negative digit values, eg ")" characters +# the string is converted back to a float to check for no illegal characters +float('%.23e' % 1e-80)