blob: ac5a74e8fc2e4f187e744ef6544f5919a70d4a8a [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)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700173 // Build negative exponent
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200174 for (e = 0, e1 = FPDECEXP; e1; e1 >>= 1, pos_pow++, neg_pow++) {
175 if (*neg_pow > f) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700176 e += e1;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200177 f *= *pos_pow;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700178 }
179 }
Dave Hylandsb2178692015-04-12 00:36:00 -0700180 char first_dig = '0';
181 char e_sign_char = '-';
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200182 if (fp_isless1(f) && f >= FPROUND_TO_ONE) {
183 f = FPCONST(1.0);
Dave Hylands9d6128a2015-08-31 15:43:31 -0700184 if (e > 1) {
185 // numbers less than 1.0 start with 0.xxx
186 first_dig = '1';
187 }
Dave Hylandsb2178692015-04-12 00:36:00 -0700188 if (e == 0) {
189 e_sign_char = '+';
190 }
Dave Hylandsca5a2412014-03-10 00:10:01 -0700191 } else {
192 e++;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200193 f *= FPCONST(10.0);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700194 }
195
196 // If the user specified 'g' format, and e is <= 4, then we'll switch
197 // to the fixed format ('f')
198
199 if (fmt == 'f' || (fmt == 'g' && e <= 4)) {
200 fmt = 'f';
201 dec = -1;
Dave Hylandsb2178692015-04-12 00:36:00 -0700202 *s++ = first_dig;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700203
204 if (prec + e + 1 > buf_remaining) {
205 prec = buf_remaining - e - 1;
206 }
207
208 if (org_fmt == 'g') {
209 prec += (e - 1);
210 }
211 num_digits = prec;
212 if (num_digits) {
213 *s++ = '.';
214 while (--e && num_digits) {
215 *s++ = '0';
216 num_digits--;
217 }
218 }
219 } else {
220 // For e & g formats, we'll be printing the exponent, so set the
221 // sign.
Dave Hylandsb2178692015-04-12 00:36:00 -0700222 e_sign = e_sign_char;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700223 dec = 0;
224
225 if (prec > (buf_remaining - 6)) {
226 prec = buf_remaining - 6;
227 if (fmt == 'g') {
228 prec++;
229 }
230 }
231 }
232 } else {
233 // Build positive exponent
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200234 for (e = 0, e1 = FPDECEXP; e1; e1 >>= 1, pos_pow++, neg_pow++) {
235 if (*pos_pow <= f) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700236 e += e1;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200237 f *= *neg_pow;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700238 }
239 }
240
241 // If the user specified fixed format (fmt == 'f') and e makes the
242 // number too big to fit into the available buffer, then we'll
243 // switch to the 'e' format.
244
245 if (fmt == 'f') {
246 if (e >= buf_remaining) {
247 fmt = 'e';
248 } else if ((e + prec + 2) > buf_remaining) {
249 prec = buf_remaining - e - 2;
250 if (prec < 0) {
251 // This means no decimal point, so we can add one back
252 // for the decimal.
253 prec++;
254 }
255 }
256 }
257 if (fmt == 'e' && prec > (buf_remaining - 6)) {
258 prec = buf_remaining - 6;
259 }
260 // If the user specified 'g' format, and e is < prec, then we'll switch
261 // to the fixed format.
262
263 if (fmt == 'g' && e < prec) {
264 fmt = 'f';
265 prec -= (e + 1);
266 }
267 if (fmt == 'f') {
268 dec = e;
269 num_digits = prec + e + 1;
270 } else {
271 e_sign = '+';
272 }
273 }
274 if (prec < 0) {
275 // This can happen when the prec is trimmed to prevent buffer overflow
276 prec = 0;
277 }
278
279 // We now have num.f as a floating point number between >= 1 and < 10
280 // (or equal to zero), and e contains the absolute value of the power of
281 // 10 exponent. and (dec + 1) == the number of dgits before the decimal.
282
283 // For e, prec is # digits after the decimal
284 // For f, prec is # digits after the decimal
285 // For g, prec is the max number of significant digits
286 //
287 // For e & g there will be a single digit before the decimal
288 // for f there will be e digits before the decimal
289
290 if (fmt == 'e') {
291 num_digits = prec + 1;
292 } else if (fmt == 'g') {
293 if (prec == 0) {
294 prec = 1;
295 }
296 num_digits = prec;
297 }
298
299 // Print the digits of the mantissa
300 for (int i = 0; i < num_digits; ++i, --dec) {
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200301 int32_t d = f;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700302 *s++ = '0' + d;
303 if (dec == 0 && prec > 0) {
304 *s++ = '.';
305 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200306 f -= (FPTYPE)d;
307 f *= FPCONST(10.0);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700308 }
309
310 // Round
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200311 if (f >= FPCONST(5.0)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700312 char *rs = s;
313 rs--;
314 while (1) {
315 if (*rs == '.') {
316 rs--;
317 continue;
318 }
319 if (*rs < '0' || *rs > '9') {
320 // + or -
321 rs++; // So we sit on the digit to the right of the sign
322 break;
323 }
324 if (*rs < '9') {
325 (*rs)++;
326 break;
327 }
328 *rs = '0';
329 if (rs == buf) {
330 break;
331 }
332 rs--;
333 }
334 if (*rs == '0') {
335 // We need to insert a 1
336 if (rs[1] == '.' && fmt != 'f') {
337 // We're going to round 9.99 to 10.00
338 // Move the decimal point
339 rs[0] = '.';
340 rs[1] = '0';
341 if (e_sign == '-') {
342 e--;
343 } else {
344 e++;
345 }
346 }
347 s++;
348 char *ss = s;
349 while (ss > rs) {
350 *ss = ss[-1];
351 ss--;
352 }
353 *rs = '1';
354 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200355 if (fp_isless1(f) && fmt == 'f') {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700356 // We rounded up to 1.0
357 prec--;
358 }
359 }
360
361 if (org_fmt == 'g' && prec > 0) {
362 // Remove trailing zeros and a trailing decimal point
363 while (s[-1] == '0') {
364 s--;
365 }
366 if (s[-1] == '.') {
367 s--;
368 }
369 }
370 // Append the exponent
371 if (e_sign) {
372 *s++ = e_char;
373 *s++ = e_sign;
374 *s++ = '0' + (e / 10);
375 *s++ = '0' + (e % 10);
376 }
377 *s = '\0';
378
379 return s - buf;
380}
381
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200382#endif // MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE