blob: 78e38831c4cff64bd2524d2cc0225c68026da7ac [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
stijn861670b2015-05-16 10:54:19 +020030#include <stdlib.h>
31#include <stdint.h>
32#include "py/formatfloat.h"
33
Damien George8bfec2b2014-03-10 13:27:02 +000034/***********************************************************************
35
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020036 Routine for converting a arbitrary floating
stijn861670b2015-05-16 10:54:19 +020037 point number into a string.
Damien George8bfec2b2014-03-10 13:27:02 +000038
Dave Hylandsca5a2412014-03-10 00:10:01 -070039 The code in this funcion was inspired from Fred Bayer's pdouble.c.
40 Since pdouble.c was released as Public Domain, I'm releasing this
41 code as public domain as well.
Damien George8bfec2b2014-03-10 13:27:02 +000042
Dave Hylandsca5a2412014-03-10 00:10:01 -070043 The original code can be found in https://github.com/dhylands/format-float
Damien George8bfec2b2014-03-10 13:27:02 +000044
Dave Hylandsca5a2412014-03-10 00:10:01 -070045 Dave Hylands
Damien George8bfec2b2014-03-10 13:27:02 +000046
Dave Hylandsca5a2412014-03-10 00:10:01 -070047***********************************************************************/
48
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020049#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
Dave Hylandsca5a2412014-03-10 00:10:01 -070050// 1 sign bit, 8 exponent bits, and 23 mantissa bits.
51// exponent values 0 and 255 are reserved, exponent can be 1 to 254.
52// exponent is stored with a bias of 127.
53// The min and max floats are on the order of 1x10^37 and 1x10^-37
54
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020055#define FPTYPE float
56#define FPCONST(x) x##F
57#define FPROUND_TO_ONE 0.9999995F
58#define FPDECEXP 32
59
Dave Hylandsca5a2412014-03-10 00:10:01 -070060#define FLT_SIGN_MASK 0x80000000
61#define FLT_EXP_MASK 0x7F800000
62#define FLT_MAN_MASK 0x007FFFFF
63
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020064union floatbits {
65 float f;
66 uint32_t u;
67};
68static inline int fp_signbit(float x) { union floatbits fb = {x}; return fb.u & FLT_SIGN_MASK; }
69static inline int fp_isspecial(float x) { union floatbits fb = {x}; return (fb.u & FLT_EXP_MASK) == FLT_EXP_MASK; }
70static inline int fp_isinf(float x) { union floatbits fb = {x}; return (fb.u & FLT_MAN_MASK) == 0; }
71static inline int fp_iszero(float x) { union floatbits fb = {x}; return fb.u == 0; }
72static inline int fp_isless1(float x) { union floatbits fb = {x}; return fb.u < 0x3f800000; }
73// Assumes both fp_isspecial() and fp_isinf() were applied before
74#define fp_isnan(x) 1
75
76#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
77
78#define FPTYPE double
79#define FPCONST(x) x
80#define FPROUND_TO_ONE 0.999999999995
81#define FPDECEXP 256
82#include <math.h>
83#define fp_signbit(x) signbit(x)
84#define fp_isspecial(x) 1
85#define fp_isnan(x) isnan(x)
86#define fp_isinf(x) isinf(x)
87#define fp_iszero(x) (x == 0)
88#define fp_isless1(x) (x < 1.0)
89
90#endif
91
92static const FPTYPE g_pos_pow[] = {
93 #if FPDECEXP > 32
94 1e256, 1e128, 1e64,
95 #endif
Dave Hylandsca5a2412014-03-10 00:10:01 -070096 1e32, 1e16, 1e8, 1e4, 1e2, 1e1
97};
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020098static const FPTYPE g_neg_pow[] = {
99 #if FPDECEXP > 32
100 1e-256, 1e-128, 1e-64,
101 #endif
Dave Hylandsca5a2412014-03-10 00:10:01 -0700102 1e-32, 1e-16, 1e-8, 1e-4, 1e-2, 1e-1
103};
104
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200105int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, char sign) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700106
107 char *s = buf;
108 int buf_remaining = buf_size - 1;
109
Dave Hylandsca5a2412014-03-10 00:10:01 -0700110 if (buf_size < 7) {
111 // Smallest exp notion is -9e+99 which is 6 chars plus terminating
Paul Sokolovskye3737b82014-07-17 17:48:35 +0300112 // null.
Dave Hylandsca5a2412014-03-10 00:10:01 -0700113
114 if (buf_size >= 2) {
115 *s++ = '?';
116 }
117 if (buf_size >= 1) {
118 *s++ = '\0';
119 }
120 return buf_size >= 2;
121 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200122 if (fp_signbit(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700123 *s++ = '-';
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200124 f = -f;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700125 } else {
126 if (sign) {
127 *s++ = sign;
128 }
129 }
130 buf_remaining -= (s - buf); // Adjust for sign
131
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200132 if (fp_isspecial(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700133 char uc = fmt & 0x20;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200134 if (fp_isinf(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700135 *s++ = 'I' ^ uc;
136 *s++ = 'N' ^ uc;
137 *s++ = 'F' ^ uc;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200138 goto ret;
139 } else if (fp_isnan(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700140 *s++ = 'N' ^ uc;
141 *s++ = 'A' ^ uc;
142 *s++ = 'N' ^ uc;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200143 ret:
144 *s = '\0';
145 return s - buf;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700146 }
Dave Hylandsca5a2412014-03-10 00:10:01 -0700147 }
148
149 if (prec < 0) {
150 prec = 6;
151 }
152 char e_char = 'E' | (fmt & 0x20); // e_char will match case of fmt
153 fmt |= 0x20; // Force fmt to be lowercase
154 char org_fmt = fmt;
155 if (fmt == 'g' && prec == 0) {
156 prec = 1;
157 }
158 int e, e1;
159 int dec = 0;
160 char e_sign = '\0';
161 int num_digits = 0;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200162 const FPTYPE *pos_pow = g_pos_pow;
163 const FPTYPE *neg_pow = g_neg_pow;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700164
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200165 if (fp_iszero(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700166 e = 0;
167 if (fmt == 'e') {
168 e_sign = '+';
169 } else if (fmt == 'f') {
170 num_digits = prec + 1;
171 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200172 } else if (fp_isless1(f)) {
Paul Sokolovsky3d6240b2015-11-22 20:02:16 +0200173 // We need to figure out what an integer digit will be used
174 // in case 'f' is used (or we revert other format to it below).
175 // As we just tested number to be <1, this is obviously 0,
176 // but we can round it up to 1 below.
177 char first_dig = '0';
178 if (f >= FPROUND_TO_ONE) {
179 first_dig = '1';
180 }
181
Dave Hylandsca5a2412014-03-10 00:10:01 -0700182 // Build negative exponent
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200183 for (e = 0, e1 = FPDECEXP; e1; e1 >>= 1, pos_pow++, neg_pow++) {
184 if (*neg_pow > f) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700185 e += e1;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200186 f *= *pos_pow;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700187 }
188 }
Dave Hylandsb2178692015-04-12 00:36:00 -0700189 char e_sign_char = '-';
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200190 if (fp_isless1(f) && f >= FPROUND_TO_ONE) {
191 f = FPCONST(1.0);
Dave Hylandsb2178692015-04-12 00:36:00 -0700192 if (e == 0) {
193 e_sign_char = '+';
194 }
Dave Hylandsca5a2412014-03-10 00:10:01 -0700195 } else {
196 e++;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200197 f *= FPCONST(10.0);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700198 }
199
200 // If the user specified 'g' format, and e is <= 4, then we'll switch
201 // to the fixed format ('f')
202
203 if (fmt == 'f' || (fmt == 'g' && e <= 4)) {
204 fmt = 'f';
205 dec = -1;
Dave Hylandsb2178692015-04-12 00:36:00 -0700206 *s++ = first_dig;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700207
208 if (prec + e + 1 > buf_remaining) {
209 prec = buf_remaining - e - 1;
210 }
211
212 if (org_fmt == 'g') {
213 prec += (e - 1);
214 }
215 num_digits = prec;
216 if (num_digits) {
217 *s++ = '.';
218 while (--e && num_digits) {
219 *s++ = '0';
220 num_digits--;
221 }
222 }
223 } else {
224 // For e & g formats, we'll be printing the exponent, so set the
225 // sign.
Dave Hylandsb2178692015-04-12 00:36:00 -0700226 e_sign = e_sign_char;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700227 dec = 0;
228
229 if (prec > (buf_remaining - 6)) {
230 prec = buf_remaining - 6;
231 if (fmt == 'g') {
232 prec++;
233 }
234 }
235 }
236 } else {
237 // Build positive exponent
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200238 for (e = 0, e1 = FPDECEXP; e1; e1 >>= 1, pos_pow++, neg_pow++) {
239 if (*pos_pow <= f) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700240 e += e1;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200241 f *= *neg_pow;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700242 }
243 }
244
245 // If the user specified fixed format (fmt == 'f') and e makes the
246 // number too big to fit into the available buffer, then we'll
247 // switch to the 'e' format.
248
249 if (fmt == 'f') {
250 if (e >= buf_remaining) {
251 fmt = 'e';
252 } else if ((e + prec + 2) > buf_remaining) {
253 prec = buf_remaining - e - 2;
254 if (prec < 0) {
255 // This means no decimal point, so we can add one back
256 // for the decimal.
257 prec++;
258 }
259 }
260 }
261 if (fmt == 'e' && prec > (buf_remaining - 6)) {
262 prec = buf_remaining - 6;
263 }
264 // If the user specified 'g' format, and e is < prec, then we'll switch
265 // to the fixed format.
266
267 if (fmt == 'g' && e < prec) {
268 fmt = 'f';
269 prec -= (e + 1);
270 }
271 if (fmt == 'f') {
272 dec = e;
273 num_digits = prec + e + 1;
274 } else {
275 e_sign = '+';
276 }
277 }
278 if (prec < 0) {
279 // This can happen when the prec is trimmed to prevent buffer overflow
280 prec = 0;
281 }
282
283 // We now have num.f as a floating point number between >= 1 and < 10
284 // (or equal to zero), and e contains the absolute value of the power of
285 // 10 exponent. and (dec + 1) == the number of dgits before the decimal.
286
287 // For e, prec is # digits after the decimal
288 // For f, prec is # digits after the decimal
289 // For g, prec is the max number of significant digits
290 //
291 // For e & g there will be a single digit before the decimal
292 // for f there will be e digits before the decimal
293
294 if (fmt == 'e') {
295 num_digits = prec + 1;
296 } else if (fmt == 'g') {
297 if (prec == 0) {
298 prec = 1;
299 }
300 num_digits = prec;
301 }
302
303 // Print the digits of the mantissa
304 for (int i = 0; i < num_digits; ++i, --dec) {
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200305 int32_t d = f;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700306 *s++ = '0' + d;
307 if (dec == 0 && prec > 0) {
308 *s++ = '.';
309 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200310 f -= (FPTYPE)d;
311 f *= FPCONST(10.0);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700312 }
313
314 // Round
Paul Sokolovsky3c4c0692015-11-22 18:09:28 +0200315 // If we print non-exponential format (i.e. 'f'), but a digit we're going
316 // to round by (e) is too far away, then there's nothing to round.
317 if ((org_fmt != 'f' || e <= 1) && f >= FPCONST(5.0)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700318 char *rs = s;
319 rs--;
320 while (1) {
321 if (*rs == '.') {
322 rs--;
323 continue;
324 }
325 if (*rs < '0' || *rs > '9') {
326 // + or -
327 rs++; // So we sit on the digit to the right of the sign
328 break;
329 }
330 if (*rs < '9') {
331 (*rs)++;
332 break;
333 }
334 *rs = '0';
335 if (rs == buf) {
336 break;
337 }
338 rs--;
339 }
340 if (*rs == '0') {
341 // We need to insert a 1
342 if (rs[1] == '.' && fmt != 'f') {
343 // We're going to round 9.99 to 10.00
344 // Move the decimal point
345 rs[0] = '.';
346 rs[1] = '0';
347 if (e_sign == '-') {
348 e--;
349 } else {
350 e++;
351 }
352 }
353 s++;
354 char *ss = s;
355 while (ss > rs) {
356 *ss = ss[-1];
357 ss--;
358 }
359 *rs = '1';
360 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200361 if (fp_isless1(f) && fmt == 'f') {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700362 // We rounded up to 1.0
363 prec--;
364 }
365 }
366
367 if (org_fmt == 'g' && prec > 0) {
368 // Remove trailing zeros and a trailing decimal point
369 while (s[-1] == '0') {
370 s--;
371 }
372 if (s[-1] == '.') {
373 s--;
374 }
375 }
376 // Append the exponent
377 if (e_sign) {
378 *s++ = e_char;
379 *s++ = e_sign;
380 *s++ = '0' + (e / 10);
381 *s++ = '0' + (e % 10);
382 }
383 *s = '\0';
384
385 return s - buf;
386}
387
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200388#endif // MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE