formatfloat.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /*
  2. * This file is part of the MicroPython 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. #include "py/mpconfig.h"
  27. #if MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE
  28. #include <assert.h>
  29. #include <stdlib.h>
  30. #include <stdint.h>
  31. #include <math.h>
  32. #include "py/formatfloat.h"
  33. /***********************************************************************
  34. Routine for converting a arbitrary floating
  35. point number into a string.
  36. The code in this funcion was inspired from Fred Bayer's pdouble.c.
  37. Since pdouble.c was released as Public Domain, I'm releasing this
  38. code as public domain as well.
  39. The original code can be found in https://github.com/dhylands/format-float
  40. Dave Hylands
  41. ***********************************************************************/
  42. #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
  43. // 1 sign bit, 8 exponent bits, and 23 mantissa bits.
  44. // exponent values 0 and 255 are reserved, exponent can be 1 to 254.
  45. // exponent is stored with a bias of 127.
  46. // The min and max floats are on the order of 1x10^37 and 1x10^-37
  47. #define FPTYPE float
  48. #define FPCONST(x) x##F
  49. #define FPROUND_TO_ONE 0.9999995F
  50. #define FPDECEXP 32
  51. #define FPMIN_BUF_SIZE 6 // +9e+99
  52. #define FLT_SIGN_MASK 0x80000000
  53. #define FLT_EXP_MASK 0x7F800000
  54. #define FLT_MAN_MASK 0x007FFFFF
  55. union floatbits {
  56. float f;
  57. uint32_t u;
  58. };
  59. static inline int fp_signbit(float x) { union floatbits fb = {x}; return fb.u & FLT_SIGN_MASK; }
  60. #define fp_isnan(x) isnan(x)
  61. #define fp_isinf(x) isinf(x)
  62. static inline int fp_iszero(float x) { union floatbits fb = {x}; return fb.u == 0; }
  63. static inline int fp_isless1(float x) { union floatbits fb = {x}; return fb.u < 0x3f800000; }
  64. #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
  65. #define FPTYPE double
  66. #define FPCONST(x) x
  67. #define FPROUND_TO_ONE 0.999999999995
  68. #define FPDECEXP 256
  69. #define FPMIN_BUF_SIZE 7 // +9e+199
  70. #define fp_signbit(x) signbit(x)
  71. #define fp_isnan(x) isnan(x)
  72. #define fp_isinf(x) isinf(x)
  73. #define fp_iszero(x) (x == 0)
  74. #define fp_isless1(x) (x < 1.0)
  75. #endif
  76. static const FPTYPE g_pos_pow[] = {
  77. #if FPDECEXP > 32
  78. 1e256, 1e128, 1e64,
  79. #endif
  80. 1e32, 1e16, 1e8, 1e4, 1e2, 1e1
  81. };
  82. static const FPTYPE g_neg_pow[] = {
  83. #if FPDECEXP > 32
  84. 1e-256, 1e-128, 1e-64,
  85. #endif
  86. 1e-32, 1e-16, 1e-8, 1e-4, 1e-2, 1e-1
  87. };
  88. int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, char sign) {
  89. char *s = buf;
  90. if (buf_size <= FPMIN_BUF_SIZE) {
  91. // FPMIN_BUF_SIZE is the minimum size needed to store any FP number.
  92. // If the buffer does not have enough room for this (plus null terminator)
  93. // then don't try to format the float.
  94. if (buf_size >= 2) {
  95. *s++ = '?';
  96. }
  97. if (buf_size >= 1) {
  98. *s = '\0';
  99. }
  100. return buf_size >= 2;
  101. }
  102. if (fp_signbit(f) && !fp_isnan(f)) {
  103. *s++ = '-';
  104. f = -f;
  105. } else {
  106. if (sign) {
  107. *s++ = sign;
  108. }
  109. }
  110. // buf_remaining contains bytes available for digits and exponent.
  111. // It is buf_size minus room for the sign and null byte.
  112. int buf_remaining = buf_size - 1 - (s - buf);
  113. {
  114. char uc = fmt & 0x20;
  115. if (fp_isinf(f)) {
  116. *s++ = 'I' ^ uc;
  117. *s++ = 'N' ^ uc;
  118. *s++ = 'F' ^ uc;
  119. goto ret;
  120. } else if (fp_isnan(f)) {
  121. *s++ = 'N' ^ uc;
  122. *s++ = 'A' ^ uc;
  123. *s++ = 'N' ^ uc;
  124. ret:
  125. *s = '\0';
  126. return s - buf;
  127. }
  128. }
  129. if (prec < 0) {
  130. prec = 6;
  131. }
  132. char e_char = 'E' | (fmt & 0x20); // e_char will match case of fmt
  133. fmt |= 0x20; // Force fmt to be lowercase
  134. char org_fmt = fmt;
  135. if (fmt == 'g' && prec == 0) {
  136. prec = 1;
  137. }
  138. int e, e1;
  139. int dec = 0;
  140. char e_sign = '\0';
  141. int num_digits = 0;
  142. const FPTYPE *pos_pow = g_pos_pow;
  143. const FPTYPE *neg_pow = g_neg_pow;
  144. if (fp_iszero(f)) {
  145. e = 0;
  146. if (fmt == 'f') {
  147. // Truncate precision to prevent buffer overflow
  148. if (prec + 2 > buf_remaining) {
  149. prec = buf_remaining - 2;
  150. }
  151. num_digits = prec + 1;
  152. } else {
  153. // Truncate precision to prevent buffer overflow
  154. if (prec + 6 > buf_remaining) {
  155. prec = buf_remaining - 6;
  156. }
  157. if (fmt == 'e') {
  158. e_sign = '+';
  159. }
  160. }
  161. } else if (fp_isless1(f)) {
  162. // We need to figure out what an integer digit will be used
  163. // in case 'f' is used (or we revert other format to it below).
  164. // As we just tested number to be <1, this is obviously 0,
  165. // but we can round it up to 1 below.
  166. char first_dig = '0';
  167. if (f >= FPROUND_TO_ONE) {
  168. first_dig = '1';
  169. }
  170. // Build negative exponent
  171. for (e = 0, e1 = FPDECEXP; e1; e1 >>= 1, pos_pow++, neg_pow++) {
  172. if (*neg_pow > f) {
  173. e += e1;
  174. f *= *pos_pow;
  175. }
  176. }
  177. char e_sign_char = '-';
  178. if (fp_isless1(f) && f >= FPROUND_TO_ONE) {
  179. f = FPCONST(1.0);
  180. if (e == 0) {
  181. e_sign_char = '+';
  182. }
  183. } else if (fp_isless1(f)) {
  184. e++;
  185. f *= FPCONST(10.0);
  186. }
  187. // If the user specified 'g' format, and e is <= 4, then we'll switch
  188. // to the fixed format ('f')
  189. if (fmt == 'f' || (fmt == 'g' && e <= 4)) {
  190. fmt = 'f';
  191. dec = -1;
  192. *s++ = first_dig;
  193. if (org_fmt == 'g') {
  194. prec += (e - 1);
  195. }
  196. // truncate precision to prevent buffer overflow
  197. if (prec + 2 > buf_remaining) {
  198. prec = buf_remaining - 2;
  199. }
  200. num_digits = prec;
  201. if (num_digits) {
  202. *s++ = '.';
  203. while (--e && num_digits) {
  204. *s++ = '0';
  205. num_digits--;
  206. }
  207. }
  208. } else {
  209. // For e & g formats, we'll be printing the exponent, so set the
  210. // sign.
  211. e_sign = e_sign_char;
  212. dec = 0;
  213. if (prec > (buf_remaining - FPMIN_BUF_SIZE)) {
  214. prec = buf_remaining - FPMIN_BUF_SIZE;
  215. if (fmt == 'g') {
  216. prec++;
  217. }
  218. }
  219. }
  220. } else {
  221. // Build positive exponent
  222. for (e = 0, e1 = FPDECEXP; e1; e1 >>= 1, pos_pow++, neg_pow++) {
  223. if (*pos_pow <= f) {
  224. e += e1;
  225. f *= *neg_pow;
  226. }
  227. }
  228. // It can be that f was right on the edge of an entry in pos_pow needs to be reduced
  229. if ((int)f >= 10) {
  230. e += 1;
  231. f *= FPCONST(0.1);
  232. }
  233. // If the user specified fixed format (fmt == 'f') and e makes the
  234. // number too big to fit into the available buffer, then we'll
  235. // switch to the 'e' format.
  236. if (fmt == 'f') {
  237. if (e >= buf_remaining) {
  238. fmt = 'e';
  239. } else if ((e + prec + 2) > buf_remaining) {
  240. prec = buf_remaining - e - 2;
  241. if (prec < 0) {
  242. // This means no decimal point, so we can add one back
  243. // for the decimal.
  244. prec++;
  245. }
  246. }
  247. }
  248. if (fmt == 'e' && prec > (buf_remaining - FPMIN_BUF_SIZE)) {
  249. prec = buf_remaining - FPMIN_BUF_SIZE;
  250. }
  251. if (fmt == 'g'){
  252. // Truncate precision to prevent buffer overflow
  253. if (prec + (FPMIN_BUF_SIZE - 1) > buf_remaining) {
  254. prec = buf_remaining - (FPMIN_BUF_SIZE - 1);
  255. }
  256. }
  257. // If the user specified 'g' format, and e is < prec, then we'll switch
  258. // to the fixed format.
  259. if (fmt == 'g' && e < prec) {
  260. fmt = 'f';
  261. prec -= (e + 1);
  262. }
  263. if (fmt == 'f') {
  264. dec = e;
  265. num_digits = prec + e + 1;
  266. } else {
  267. e_sign = '+';
  268. }
  269. }
  270. if (prec < 0) {
  271. // This can happen when the prec is trimmed to prevent buffer overflow
  272. prec = 0;
  273. }
  274. // We now have num.f as a floating point number between >= 1 and < 10
  275. // (or equal to zero), and e contains the absolute value of the power of
  276. // 10 exponent. and (dec + 1) == the number of dgits before the decimal.
  277. // For e, prec is # digits after the decimal
  278. // For f, prec is # digits after the decimal
  279. // For g, prec is the max number of significant digits
  280. //
  281. // For e & g there will be a single digit before the decimal
  282. // for f there will be e digits before the decimal
  283. if (fmt == 'e') {
  284. num_digits = prec + 1;
  285. } else if (fmt == 'g') {
  286. if (prec == 0) {
  287. prec = 1;
  288. }
  289. num_digits = prec;
  290. }
  291. // Print the digits of the mantissa
  292. for (int i = 0; i < num_digits; ++i, --dec) {
  293. int32_t d = (int32_t)f;
  294. if (d < 0) {
  295. *s++ = '0';
  296. } else {
  297. *s++ = '0' + d;
  298. }
  299. if (dec == 0 && prec > 0) {
  300. *s++ = '.';
  301. }
  302. f -= (FPTYPE)d;
  303. f *= FPCONST(10.0);
  304. }
  305. // Round
  306. // If we print non-exponential format (i.e. 'f'), but a digit we're going
  307. // to round by (e) is too far away, then there's nothing to round.
  308. if ((org_fmt != 'f' || e <= num_digits) && f >= FPCONST(5.0)) {
  309. char *rs = s;
  310. rs--;
  311. while (1) {
  312. if (*rs == '.') {
  313. rs--;
  314. continue;
  315. }
  316. if (*rs < '0' || *rs > '9') {
  317. // + or -
  318. rs++; // So we sit on the digit to the right of the sign
  319. break;
  320. }
  321. if (*rs < '9') {
  322. (*rs)++;
  323. break;
  324. }
  325. *rs = '0';
  326. if (rs == buf) {
  327. break;
  328. }
  329. rs--;
  330. }
  331. if (*rs == '0') {
  332. // We need to insert a 1
  333. if (rs[1] == '.' && fmt != 'f') {
  334. // We're going to round 9.99 to 10.00
  335. // Move the decimal point
  336. rs[0] = '.';
  337. rs[1] = '0';
  338. if (e_sign == '-') {
  339. e--;
  340. if (e == 0) {
  341. e_sign = '+';
  342. }
  343. } else {
  344. e++;
  345. }
  346. } else {
  347. // Need at extra digit at the end to make room for the leading '1'
  348. s++;
  349. }
  350. char *ss = s;
  351. while (ss > rs) {
  352. *ss = ss[-1];
  353. ss--;
  354. }
  355. *rs = '1';
  356. }
  357. }
  358. // verify that we did not overrun the input buffer so far
  359. assert((size_t)(s + 1 - buf) <= buf_size);
  360. if (org_fmt == 'g' && prec > 0) {
  361. // Remove trailing zeros and a trailing decimal point
  362. while (s[-1] == '0') {
  363. s--;
  364. }
  365. if (s[-1] == '.') {
  366. s--;
  367. }
  368. }
  369. // Append the exponent
  370. if (e_sign) {
  371. *s++ = e_char;
  372. *s++ = e_sign;
  373. if (FPMIN_BUF_SIZE == 7 && e >= 100) {
  374. *s++ = '0' + (e / 100);
  375. }
  376. *s++ = '0' + ((e / 10) % 10);
  377. *s++ = '0' + (e % 10);
  378. }
  379. *s = '\0';
  380. // verify that we did not overrun the input buffer
  381. assert((size_t)(s + 1 - buf) <= buf_size);
  382. return s - buf;
  383. }
  384. #endif // MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE