blob: b16746b39b1a96b8dbdf54dade23f7f61aaab682 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020027#include "py/mpconfig.h"
28#if MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE
29
Damien Georgecea6cf82016-03-15 12:21:56 +000030#include <assert.h>
stijn861670b2015-05-16 10:54:19 +020031#include <stdlib.h>
32#include <stdint.h>
33#include "py/formatfloat.h"
34
Damien George8bfec2b2014-03-10 13:27:02 +000035/***********************************************************************
36
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020037 Routine for converting a arbitrary floating
stijn861670b2015-05-16 10:54:19 +020038 point number into a string.
Damien George8bfec2b2014-03-10 13:27:02 +000039
Dave Hylandsca5a2412014-03-10 00:10:01 -070040 The code in this funcion was inspired from Fred Bayer's pdouble.c.
41 Since pdouble.c was released as Public Domain, I'm releasing this
42 code as public domain as well.
Damien George8bfec2b2014-03-10 13:27:02 +000043
Dave Hylandsca5a2412014-03-10 00:10:01 -070044 The original code can be found in https://github.com/dhylands/format-float
Damien George8bfec2b2014-03-10 13:27:02 +000045
Dave Hylandsca5a2412014-03-10 00:10:01 -070046 Dave Hylands
Damien George8bfec2b2014-03-10 13:27:02 +000047
Dave Hylandsca5a2412014-03-10 00:10:01 -070048***********************************************************************/
49
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020050#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
Dave Hylandsca5a2412014-03-10 00:10:01 -070051// 1 sign bit, 8 exponent bits, and 23 mantissa bits.
52// exponent values 0 and 255 are reserved, exponent can be 1 to 254.
53// exponent is stored with a bias of 127.
54// The min and max floats are on the order of 1x10^37 and 1x10^-37
55
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020056#define FPTYPE float
57#define FPCONST(x) x##F
58#define FPROUND_TO_ONE 0.9999995F
59#define FPDECEXP 32
Damien George7417ccf2016-01-29 11:39:12 +000060#define FPMIN_BUF_SIZE 6 // +9e+99
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020061
Dave Hylandsca5a2412014-03-10 00:10:01 -070062#define FLT_SIGN_MASK 0x80000000
63#define FLT_EXP_MASK 0x7F800000
64#define FLT_MAN_MASK 0x007FFFFF
65
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020066union floatbits {
67 float f;
68 uint32_t u;
69};
70static inline int fp_signbit(float x) { union floatbits fb = {x}; return fb.u & FLT_SIGN_MASK; }
71static inline int fp_isspecial(float x) { union floatbits fb = {x}; return (fb.u & FLT_EXP_MASK) == FLT_EXP_MASK; }
72static inline int fp_isinf(float x) { union floatbits fb = {x}; return (fb.u & FLT_MAN_MASK) == 0; }
73static inline int fp_iszero(float x) { union floatbits fb = {x}; return fb.u == 0; }
74static inline int fp_isless1(float x) { union floatbits fb = {x}; return fb.u < 0x3f800000; }
75// Assumes both fp_isspecial() and fp_isinf() were applied before
76#define fp_isnan(x) 1
77
78#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
79
80#define FPTYPE double
81#define FPCONST(x) x
82#define FPROUND_TO_ONE 0.999999999995
83#define FPDECEXP 256
Damien George7417ccf2016-01-29 11:39:12 +000084#define FPMIN_BUF_SIZE 7 // +9e+199
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020085#include <math.h>
86#define fp_signbit(x) signbit(x)
87#define fp_isspecial(x) 1
88#define fp_isnan(x) isnan(x)
89#define fp_isinf(x) isinf(x)
90#define fp_iszero(x) (x == 0)
91#define fp_isless1(x) (x < 1.0)
92
93#endif
94
95static const FPTYPE g_pos_pow[] = {
96 #if FPDECEXP > 32
97 1e256, 1e128, 1e64,
98 #endif
Dave Hylandsca5a2412014-03-10 00:10:01 -070099 1e32, 1e16, 1e8, 1e4, 1e2, 1e1
100};
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200101static const FPTYPE g_neg_pow[] = {
102 #if FPDECEXP > 32
103 1e-256, 1e-128, 1e-64,
104 #endif
Dave Hylandsca5a2412014-03-10 00:10:01 -0700105 1e-32, 1e-16, 1e-8, 1e-4, 1e-2, 1e-1
106};
107
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200108int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, char sign) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700109
110 char *s = buf;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700111
Damien George7417ccf2016-01-29 11:39:12 +0000112 if (buf_size <= FPMIN_BUF_SIZE) {
113 // FPMIN_BUF_SIZE is the minimum size needed to store any FP number.
114 // If the buffer does not have enough room for this (plus null terminator)
115 // then don't try to format the float.
Dave Hylandsca5a2412014-03-10 00:10:01 -0700116
117 if (buf_size >= 2) {
118 *s++ = '?';
119 }
120 if (buf_size >= 1) {
121 *s++ = '\0';
122 }
123 return buf_size >= 2;
124 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200125 if (fp_signbit(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700126 *s++ = '-';
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200127 f = -f;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700128 } else {
129 if (sign) {
130 *s++ = sign;
131 }
132 }
Damien George7417ccf2016-01-29 11:39:12 +0000133
134 // buf_remaining contains bytes available for digits and exponent.
135 // It is buf_size minus room for the sign and null byte.
136 int buf_remaining = buf_size - 1 - (s - buf);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700137
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200138 if (fp_isspecial(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700139 char uc = fmt & 0x20;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200140 if (fp_isinf(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700141 *s++ = 'I' ^ uc;
142 *s++ = 'N' ^ uc;
143 *s++ = 'F' ^ uc;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200144 goto ret;
145 } else if (fp_isnan(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700146 *s++ = 'N' ^ uc;
147 *s++ = 'A' ^ uc;
148 *s++ = 'N' ^ uc;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200149 ret:
150 *s = '\0';
151 return s - buf;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700152 }
Dave Hylandsca5a2412014-03-10 00:10:01 -0700153 }
154
155 if (prec < 0) {
156 prec = 6;
157 }
158 char e_char = 'E' | (fmt & 0x20); // e_char will match case of fmt
159 fmt |= 0x20; // Force fmt to be lowercase
160 char org_fmt = fmt;
161 if (fmt == 'g' && prec == 0) {
162 prec = 1;
163 }
164 int e, e1;
165 int dec = 0;
166 char e_sign = '\0';
167 int num_digits = 0;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200168 const FPTYPE *pos_pow = g_pos_pow;
169 const FPTYPE *neg_pow = g_neg_pow;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700170
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200171 if (fp_iszero(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700172 e = 0;
Damien Georgee1e76572016-03-29 22:07:15 +0100173 if (fmt == 'f') {
174 // Truncate precision to prevent buffer overflow
175 if (prec + 2 > buf_remaining) {
176 prec = buf_remaining - 2;
177 }
Dave Hylandsca5a2412014-03-10 00:10:01 -0700178 num_digits = prec + 1;
Damien Georgee1e76572016-03-29 22:07:15 +0100179 } else {
180 // Truncate precision to prevent buffer overflow
181 if (prec + 6 > buf_remaining) {
182 prec = buf_remaining - 6;
183 }
184 if (fmt == 'e') {
185 e_sign = '+';
186 }
Dave Hylandsca5a2412014-03-10 00:10:01 -0700187 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200188 } else if (fp_isless1(f)) {
Paul Sokolovsky3d6240b2015-11-22 20:02:16 +0200189 // We need to figure out what an integer digit will be used
190 // in case 'f' is used (or we revert other format to it below).
191 // As we just tested number to be <1, this is obviously 0,
192 // but we can round it up to 1 below.
193 char first_dig = '0';
194 if (f >= FPROUND_TO_ONE) {
195 first_dig = '1';
196 }
197
Dave Hylandsca5a2412014-03-10 00:10:01 -0700198 // Build negative exponent
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200199 for (e = 0, e1 = FPDECEXP; e1; e1 >>= 1, pos_pow++, neg_pow++) {
200 if (*neg_pow > f) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700201 e += e1;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200202 f *= *pos_pow;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700203 }
204 }
Dave Hylandsb2178692015-04-12 00:36:00 -0700205 char e_sign_char = '-';
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200206 if (fp_isless1(f) && f >= FPROUND_TO_ONE) {
207 f = FPCONST(1.0);
Dave Hylandsb2178692015-04-12 00:36:00 -0700208 if (e == 0) {
209 e_sign_char = '+';
210 }
Damien George03b8bb72016-03-29 22:03:13 +0100211 } else if (fp_isless1(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700212 e++;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200213 f *= FPCONST(10.0);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700214 }
215
216 // If the user specified 'g' format, and e is <= 4, then we'll switch
217 // to the fixed format ('f')
218
219 if (fmt == 'f' || (fmt == 'g' && e <= 4)) {
220 fmt = 'f';
221 dec = -1;
Dave Hylandsb2178692015-04-12 00:36:00 -0700222 *s++ = first_dig;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700223
Dave Hylandsca5a2412014-03-10 00:10:01 -0700224 if (org_fmt == 'g') {
225 prec += (e - 1);
226 }
Damien Georgecea6cf82016-03-15 12:21:56 +0000227
228 // truncate precision to prevent buffer overflow
229 if (prec + 2 > buf_remaining) {
230 prec = buf_remaining - 2;
231 }
232
Dave Hylandsca5a2412014-03-10 00:10:01 -0700233 num_digits = prec;
234 if (num_digits) {
235 *s++ = '.';
236 while (--e && num_digits) {
237 *s++ = '0';
238 num_digits--;
239 }
240 }
241 } else {
242 // For e & g formats, we'll be printing the exponent, so set the
243 // sign.
Dave Hylandsb2178692015-04-12 00:36:00 -0700244 e_sign = e_sign_char;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700245 dec = 0;
246
Damien George7417ccf2016-01-29 11:39:12 +0000247 if (prec > (buf_remaining - FPMIN_BUF_SIZE)) {
248 prec = buf_remaining - FPMIN_BUF_SIZE;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700249 if (fmt == 'g') {
250 prec++;
251 }
252 }
253 }
254 } else {
255 // Build positive exponent
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200256 for (e = 0, e1 = FPDECEXP; e1; e1 >>= 1, pos_pow++, neg_pow++) {
257 if (*pos_pow <= f) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700258 e += e1;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200259 f *= *neg_pow;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700260 }
261 }
262
Damien George03b8bb72016-03-29 22:03:13 +0100263 // It can be that f was right on the edge of an entry in pos_pow needs to be reduced
264 if (f >= FPCONST(10.0)) {
265 e += 1;
266 f *= FPCONST(0.1);
267 }
268
Dave Hylandsca5a2412014-03-10 00:10:01 -0700269 // If the user specified fixed format (fmt == 'f') and e makes the
270 // number too big to fit into the available buffer, then we'll
271 // switch to the 'e' format.
272
273 if (fmt == 'f') {
274 if (e >= buf_remaining) {
275 fmt = 'e';
276 } else if ((e + prec + 2) > buf_remaining) {
277 prec = buf_remaining - e - 2;
278 if (prec < 0) {
279 // This means no decimal point, so we can add one back
280 // for the decimal.
281 prec++;
282 }
283 }
284 }
Damien George7417ccf2016-01-29 11:39:12 +0000285 if (fmt == 'e' && prec > (buf_remaining - FPMIN_BUF_SIZE)) {
286 prec = buf_remaining - FPMIN_BUF_SIZE;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700287 }
Damien Georgee1e76572016-03-29 22:07:15 +0100288 if (fmt == 'g'){
289 // Truncate precision to prevent buffer overflow
290 if (prec + (FPMIN_BUF_SIZE - 1) > buf_remaining) {
291 prec = buf_remaining - (FPMIN_BUF_SIZE - 1);
292 }
293 }
Dave Hylandsca5a2412014-03-10 00:10:01 -0700294 // If the user specified 'g' format, and e is < prec, then we'll switch
295 // to the fixed format.
296
297 if (fmt == 'g' && e < prec) {
298 fmt = 'f';
299 prec -= (e + 1);
300 }
301 if (fmt == 'f') {
302 dec = e;
303 num_digits = prec + e + 1;
304 } else {
305 e_sign = '+';
306 }
307 }
308 if (prec < 0) {
309 // This can happen when the prec is trimmed to prevent buffer overflow
310 prec = 0;
311 }
312
313 // We now have num.f as a floating point number between >= 1 and < 10
314 // (or equal to zero), and e contains the absolute value of the power of
315 // 10 exponent. and (dec + 1) == the number of dgits before the decimal.
316
317 // For e, prec is # digits after the decimal
318 // For f, prec is # digits after the decimal
319 // For g, prec is the max number of significant digits
320 //
321 // For e & g there will be a single digit before the decimal
322 // for f there will be e digits before the decimal
323
324 if (fmt == 'e') {
325 num_digits = prec + 1;
326 } else if (fmt == 'g') {
327 if (prec == 0) {
328 prec = 1;
329 }
330 num_digits = prec;
331 }
332
333 // Print the digits of the mantissa
334 for (int i = 0; i < num_digits; ++i, --dec) {
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200335 int32_t d = f;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700336 *s++ = '0' + d;
337 if (dec == 0 && prec > 0) {
338 *s++ = '.';
339 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200340 f -= (FPTYPE)d;
341 f *= FPCONST(10.0);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700342 }
343
344 // Round
Paul Sokolovsky3c4c0692015-11-22 18:09:28 +0200345 // If we print non-exponential format (i.e. 'f'), but a digit we're going
346 // to round by (e) is too far away, then there's nothing to round.
347 if ((org_fmt != 'f' || e <= 1) && f >= FPCONST(5.0)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700348 char *rs = s;
349 rs--;
350 while (1) {
351 if (*rs == '.') {
352 rs--;
353 continue;
354 }
355 if (*rs < '0' || *rs > '9') {
356 // + or -
357 rs++; // So we sit on the digit to the right of the sign
358 break;
359 }
360 if (*rs < '9') {
361 (*rs)++;
362 break;
363 }
364 *rs = '0';
365 if (rs == buf) {
366 break;
367 }
368 rs--;
369 }
370 if (*rs == '0') {
371 // We need to insert a 1
372 if (rs[1] == '.' && fmt != 'f') {
373 // We're going to round 9.99 to 10.00
374 // Move the decimal point
375 rs[0] = '.';
376 rs[1] = '0';
377 if (e_sign == '-') {
378 e--;
Damien George6ed45812017-06-13 13:36:56 +1000379 if (e == 0) {
380 e_sign = '+';
381 }
Dave Hylandsca5a2412014-03-10 00:10:01 -0700382 } else {
383 e++;
384 }
Damien George6ed45812017-06-13 13:36:56 +1000385 } else {
386 // Need at extra digit at the end to make room for the leading '1'
387 s++;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700388 }
Dave Hylandsca5a2412014-03-10 00:10:01 -0700389 char *ss = s;
390 while (ss > rs) {
391 *ss = ss[-1];
392 ss--;
393 }
394 *rs = '1';
395 }
Dave Hylandsca5a2412014-03-10 00:10:01 -0700396 }
397
Damien Georgee1e76572016-03-29 22:07:15 +0100398 // verify that we did not overrun the input buffer so far
399 assert((size_t)(s + 1 - buf) <= buf_size);
400
Dave Hylandsca5a2412014-03-10 00:10:01 -0700401 if (org_fmt == 'g' && prec > 0) {
402 // Remove trailing zeros and a trailing decimal point
403 while (s[-1] == '0') {
404 s--;
405 }
406 if (s[-1] == '.') {
407 s--;
408 }
409 }
410 // Append the exponent
411 if (e_sign) {
412 *s++ = e_char;
413 *s++ = e_sign;
Damien George7417ccf2016-01-29 11:39:12 +0000414 if (FPMIN_BUF_SIZE == 7 && e >= 100) {
415 *s++ = '0' + (e / 100);
416 }
417 *s++ = '0' + ((e / 10) % 10);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700418 *s++ = '0' + (e % 10);
419 }
420 *s = '\0';
421
Damien Georgecea6cf82016-03-15 12:21:56 +0000422 // verify that we did not overrun the input buffer
423 assert((size_t)(s + 1 - buf) <= buf_size);
424
Dave Hylandsca5a2412014-03-10 00:10:01 -0700425 return s - buf;
426}
427
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200428#endif // MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE