Remove unistd.h
[helenos.git] / uspace / lib / c / generic / double_to_str.c
blobe4de3f86a5723c28973bc9bad81384c7f04a8fdc
1 /*
2 * Copyright (c) 2012 Adam Hraska
3 * All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <double_to_str.h>
31 #include "private/power_of_ten.h"
32 #include <ieee_double.h>
34 #include <stdint.h>
35 #include <stdbool.h>
36 #include <stddef.h>
37 #include <assert.h>
40 * Floating point numbers are converted from their binary representation
41 * into a decimal string using the algorithm described in:
42 * Printing floating-point numbers quickly and accurately with integers
43 * Loitsch, 2010
46 /** The computation assumes a significand of 64 bits. */
47 static const int significand_width = 64;
49 /* Scale exponents to interval [alpha, gamma] to simplify conversion. */
50 static const int alpha = -59;
51 static const int gamma = -32;
54 /** Returns true if the most-significant bit of num.significand is set. */
55 static bool is_normalized(fp_num_t num)
57 assert(8*sizeof(num.significand) == significand_width);
59 /* Normalized == most significant bit of the significand is set. */
60 return (num.significand & (1ULL << (significand_width - 1))) != 0;
63 /** Returns a normalized num with the MSbit set. */
64 static fp_num_t normalize(fp_num_t num)
66 const uint64_t top10bits = 0xffc0000000000000ULL;
68 /* num usually comes from ieee_double with top 10 bits zero. */
69 while (0 == (num.significand & top10bits)) {
70 num.significand <<= 10;
71 num.exponent -= 10;
74 while (!is_normalized(num)) {
75 num.significand <<= 1;
76 --num.exponent;
79 return num;
83 /** Returns x * y with an error of less than 0.5 ulp. */
84 static fp_num_t multiply(fp_num_t x, fp_num_t y)
86 assert(/* is_normalized(x) && */ is_normalized(y));
88 const uint32_t low_bits = -1;
90 uint64_t a, b, c, d;
91 a = x.significand >> 32;
92 b = x.significand & low_bits;
93 c = y.significand >> 32;
94 d = y.significand & low_bits;
96 uint64_t bd, ad, bc, ac;
97 bd = b * d;
98 ad = a * d;
100 bc = b * c;
101 ac = a * c;
103 /* Denote 32 bit parts of x a y as: x == a b, y == c d. Then:
104 * a b
105 * * c d
106 * ----------
107 * ad bd .. multiplication of 32bit parts results in 64bit parts
108 * + ac bc
109 * ----------
110 * [b|d] .. Depicts 64 bit intermediate results and how
111 * [a|d] the 32 bit parts of these results overlap and
112 * [b|c] contribute to the final result.
113 * +[a|c]
114 * ----------
115 * [ret]
116 * [tmp]
118 uint64_t tmp = (bd >> 32) + (ad & low_bits) + (bc & low_bits);
120 /* Round upwards. */
121 tmp += 1U << 31;
123 fp_num_t ret;
124 ret.significand = ac + (bc >> 32) + (ad >> 32) + (tmp >> 32);
125 ret.exponent = x.exponent + y.exponent + significand_width;
127 return ret;
131 /** Returns a - b. Both must have the same exponent. */
132 static fp_num_t subtract(fp_num_t a, fp_num_t b)
134 assert(a.exponent == b.exponent);
135 assert(a.significand >= b.significand);
137 fp_num_t result;
139 result.significand = a.significand - b.significand;
140 result.exponent = a.exponent;
142 return result;
146 /** Returns the interval [low, high] of numbers that convert to binary val. */
147 static void get_normalized_bounds(ieee_double_t val, fp_num_t *high,
148 fp_num_t *low, fp_num_t *val_dist)
151 * Only works if val comes directly from extract_ieee_double without
152 * being manipulated in any way (eg it must not be normalized).
154 assert(!is_normalized(val.pos_val));
156 high->significand = (val.pos_val.significand << 1) + 1;
157 high->exponent = val.pos_val.exponent - 1;
159 /* val_dist = high - val */
160 val_dist->significand = 1;
161 val_dist->exponent = val.pos_val.exponent - 1;
163 /* Distance from both lower and upper bound is the same. */
164 if (!val.is_accuracy_step) {
165 low->significand = (val.pos_val.significand << 1) - 1;
166 low->exponent = val.pos_val.exponent - 1;
167 } else {
168 low->significand = (val.pos_val.significand << 2) - 1;
169 low->exponent = val.pos_val.exponent - 2;
172 *high = normalize(*high);
175 * Lower bound may not be normalized if subtracting 1 unit
176 * reset the most-significant bit to 0.
178 low->significand = low->significand << (low->exponent - high->exponent);
179 low->exponent = high->exponent;
181 val_dist->significand =
182 val_dist->significand << (val_dist->exponent - high->exponent);
183 val_dist->exponent = high->exponent;
186 /** Determines the interval of numbers that have the binary representation
187 * of val.
189 * Numbers in the range [scaled_upper_bound - bounds_delta, scaled_upper_bound]
190 * have the same double binary representation as val.
192 * Bounds are scaled by 10^scale so that alpha <= exponent <= gamma.
193 * Moreover, scaled_upper_bound is normalized.
195 * val_dist is the scaled distance from val to the upper bound, ie
196 * val_dist == (upper_bound - val) * 10^scale
198 static void calc_scaled_bounds(ieee_double_t val, fp_num_t *scaled_upper_bound,
199 fp_num_t *bounds_delta, fp_num_t *val_dist, int *scale)
201 fp_num_t upper_bound, lower_bound;
203 get_normalized_bounds(val, &upper_bound, &lower_bound, val_dist);
205 assert(upper_bound.exponent == lower_bound.exponent);
206 assert(is_normalized(upper_bound));
207 assert(normalize(val.pos_val).exponent == upper_bound.exponent);
210 * Find such a cached normalized power of 10 that if multiplied
211 * by upper_bound the binary exponent of upper_bound almost vanishes,
212 * ie:
213 * upper_scaled := upper_bound * 10^scale
214 * alpha <= upper_scaled.exponent <= gamma
215 * alpha <= upper_bound.exponent + pow_10.exponent + 64 <= gamma
217 fp_num_t scaling_power_of_10;
218 int lower_bin_exp = alpha - upper_bound.exponent - significand_width;
220 get_power_of_ten(lower_bin_exp, &scaling_power_of_10, scale);
222 int scale_exp = scaling_power_of_10.exponent;
223 assert(alpha <= upper_bound.exponent + scale_exp + significand_width);
224 assert(upper_bound.exponent + scale_exp + significand_width <= gamma);
226 fp_num_t upper_scaled = multiply(upper_bound, scaling_power_of_10);
227 fp_num_t lower_scaled = multiply(lower_bound, scaling_power_of_10);
228 *val_dist = multiply(*val_dist, scaling_power_of_10);
230 assert(alpha <= upper_scaled.exponent && upper_scaled.exponent <= gamma);
233 * Any value between lower and upper bound would be represented
234 * in binary as the double val originated from. The bounds were
235 * however scaled by an imprecise power of 10 (error less than
236 * 1 ulp) so the scaled bounds have an error of less than 1 ulp.
237 * Conservatively round the lower bound up and the upper bound
238 * down by 1 ulp just to be on the safe side. It avoids pronouncing
239 * produced decimal digits as correct if such a decimal number
240 * is close to the bounds to within 1 ulp.
242 upper_scaled.significand -= 1;
243 lower_scaled.significand += 1;
245 *bounds_delta = subtract(upper_scaled, lower_scaled);
246 *scaled_upper_bound = upper_scaled;
250 /** Rounds the last digit of buf so that it is closest to the converted number.*/
251 static void round_last_digit(uint64_t rest, uint64_t w_dist, uint64_t delta,
252 uint64_t digit_val_diff, char *buf, int len)
255 * | <------- delta -------> |
256 * | | <---- w_dist ----> |
257 * | | | <- rest -> |
258 * | | | |
259 * | | ` buffer |
260 * | ` w ` upper
261 * ` lower
263 * delta = upper - lower .. conservative/safe interval
264 * w_dist = upper - w
265 * upper = "number represented by digits in buf" + rest
267 * Changing buf[len - 1] changes the value represented by buf
268 * by digit_val_diff * scaling, where scaling is shared by
269 * all parameters.
273 /* Current number in buf is greater than the double being converted */
274 bool cur_greater_w = rest < w_dist;
275 /* Rounding down by one would keep buf in between bounds (in safe rng). */
276 bool next_in_val_rng = cur_greater_w && (rest + digit_val_diff < delta);
277 /* Rounding down by one would bring buf closer to the processed number. */
278 bool next_closer = next_in_val_rng
279 && (rest + digit_val_diff < w_dist || rest - w_dist < w_dist - rest);
281 /* Of the shortest strings pick the one that is closest to the actual
282 floating point number. */
283 while (next_closer) {
284 assert('0' < buf[len - 1]);
285 assert(0 < digit_val_diff);
287 --buf[len - 1];
288 rest += digit_val_diff;
290 cur_greater_w = rest < w_dist;
291 next_in_val_rng = cur_greater_w && (rest + digit_val_diff < delta);
292 next_closer = next_in_val_rng
293 && (rest + digit_val_diff < w_dist || rest - w_dist < w_dist - rest);
298 /** Generates the shortest accurate decimal string representation.
300 * Outputs (mostly) the shortest accurate string representation
301 * for the number scaled_upper - val_dist. Numbers in the interval
302 * [scaled_upper - delta, scaled_upper] have the same binary
303 * floating point representation and will therefore share the
304 * shortest string representation (up to the rounding of the last
305 * digit to bring the shortest string also the closest to the
306 * actual number).
308 * @param scaled_upper Scaled upper bound of numbers that have the
309 * same binary representation as the converted number.
310 * Scaled by 10^-scale so that alpha <= exponent <= gamma.
311 * @param delta scaled_upper - delta is the lower bound of numbers
312 * that share the same binary representation in double.
313 * @param val_dist scaled_upper - val_dist is the number whose
314 * decimal string we're generating.
315 * @param scale Decimal scaling of the value to convert (ie scaled_upper).
316 * @param buf Buffer to store the string representation. Must be large
317 * enough to store all digits and a null terminator. At most
318 * MAX_DOUBLE_STR_LEN digits will be written (not counting
319 * the null terminator).
320 * @param buf_size Size of buf in bytes.
321 * @param dec_exponent Will be set to the decimal exponent of the number
322 * string in buf.
324 * @return Number of digits; negative on failure (eg buffer too small).
326 static int gen_dec_digits(fp_num_t scaled_upper, fp_num_t delta,
327 fp_num_t val_dist, int scale, char *buf, size_t buf_size, int *dec_exponent)
330 * The integral part of scaled_upper is 5 to 32 bits long while
331 * the remaining fractional part is 59 to 32 bits long because:
332 * -59 == alpha <= scaled_upper.e <= gamma == -32
334 * | <------- delta -------> |
335 * | | <--- val_dist ---> |
336 * | | |<- remainder ->|
337 * | | | |
338 * | | ` buffer |
339 * | ` val ` upper
340 * ` lower
343 assert(scaled_upper.significand != 0);
344 assert(alpha <= scaled_upper.exponent && scaled_upper.exponent <= gamma);
345 assert(scaled_upper.exponent == delta.exponent);
346 assert(scaled_upper.exponent == val_dist.exponent);
347 assert(val_dist.significand <= delta.significand);
349 /* We'll produce at least one digit and a null terminator. */
350 if (buf_size < 2) {
351 return -1;
354 /* one is number 1 encoded with the same exponent as scaled_upper */
355 fp_num_t one;
356 one.significand = ((uint64_t) 1) << (-scaled_upper.exponent);
357 one.exponent = scaled_upper.exponent;
360 * Extract the integral part of scaled_upper.
361 * upper / one == upper >> -one.e
363 uint32_t int_part = (uint32_t)(scaled_upper.significand >> (-one.exponent));
366 * Fractional part of scaled_upper.
367 * upper % one == upper & (one.f - 1)
369 uint64_t frac_part = scaled_upper.significand & (one.significand - 1);
372 * The integral part of upper has at least 5 bits (64 + alpha) and
373 * at most 32 bits (64 + gamma). The integral part has at most 10
374 * decimal digits, so kappa <= 10.
376 int kappa = 10;
377 uint32_t div = 1000000000;
378 size_t len = 0;
380 /* Produce decimal digits for the integral part of upper. */
381 while (kappa > 0) {
382 int digit = int_part / div;
383 int_part %= div;
385 --kappa;
387 /* Skip leading zeros. */
388 if (digit != 0 || len != 0) {
389 /* Current length + new digit + null terminator <= buf_size */
390 if (len + 2 <= buf_size) {
391 buf[len] = '0' + digit;
392 ++len;
393 } else {
394 return -1;
399 * Difference between the so far produced decimal number and upper
400 * is calculated as: remaining_int_part * one + frac_part
402 uint64_t remainder = (((uint64_t)int_part) << -one.exponent) + frac_part;
404 /* The produced decimal number would convert back to upper. */
405 if (remainder <= delta.significand) {
406 assert(0 < len && len < buf_size);
407 *dec_exponent = kappa - scale;
408 buf[len] = '\0';
410 /* Of the shortest representations choose the numerically closest. */
411 round_last_digit(remainder, val_dist.significand, delta.significand,
412 (uint64_t)div << (-one.exponent), buf, len);
413 return len;
416 div /= 10;
419 /* Generate decimal digits for the fractional part of upper. */
420 do {
422 * Does not overflow because at least 5 upper bits were
423 * taken by the integral part and are now unused in frac_part.
425 frac_part *= 10;
426 delta.significand *= 10;
427 val_dist.significand *= 10;
429 /* frac_part / one */
430 int digit = (int)(frac_part >> (-one.exponent));
432 /* frac_part %= one */
433 frac_part &= one.significand - 1;
435 --kappa;
437 /* Skip leading zeros. */
438 if (digit == 0 && len == 0) {
439 continue;
442 /* Current length + new digit + null terminator <= buf_size */
443 if (len + 2 <= buf_size) {
444 buf[len] = '0' + digit;
445 ++len;
446 } else {
447 return -1;
449 } while (frac_part > delta.significand);
451 assert(0 < len && len < buf_size);
453 *dec_exponent = kappa - scale;
454 buf[len] = '\0';
456 /* Of the shortest representations choose the numerically closest one. */
457 round_last_digit(frac_part, val_dist.significand, delta.significand,
458 one.significand, buf, len);
460 return len;
463 /** Produce a string for 0.0 */
464 static int zero_to_str(char *buf, size_t buf_size, int *dec_exponent)
466 if (2 <= buf_size) {
467 buf[0] = '0';
468 buf[1] = '\0';
469 *dec_exponent = 0;
470 return 1;
471 } else {
472 return -1;
477 /** Converts a non-special double into its shortest accurate string
478 * representation.
480 * Produces an accurate string representation, ie the string will
481 * convert back to the same binary double (eg via strtod). In the
482 * vast majority of cases (99%) the string will be the shortest such
483 * string that is also the closest to the value of any shortest
484 * string representations. Therefore, no trailing zeros are ever
485 * produced.
487 * Conceptually, the value is: buf * 10^dec_exponent
489 * Never outputs trailing zeros.
491 * @param ieee_val Binary double description to convert. Must be the product
492 * of extract_ieee_double and it must not be a special number.
493 * @param buf Buffer to store the string representation. Must be large
494 * enough to store all digits and a null terminator. At most
495 * MAX_DOUBLE_STR_LEN digits will be written (not counting
496 * the null terminator).
497 * @param buf_size Size of buf in bytes.
498 * @param dec_exponent Will be set to the decimal exponent of the number
499 * string in buf.
501 * @return The number of printed digits. A negative value indicates
502 * an error: buf too small (or ieee_val.is_special).
504 int double_to_short_str(ieee_double_t ieee_val, char *buf, size_t buf_size,
505 int *dec_exponent)
507 /* The whole computation assumes 64bit significand. */
508 static_assert(sizeof(ieee_val.pos_val.significand) == sizeof(uint64_t));
510 if (ieee_val.is_special) {
511 return -1;
514 /* Zero cannot be normalized. Handle it here. */
515 if (0 == ieee_val.pos_val.significand) {
516 return zero_to_str(buf, buf_size, dec_exponent);
519 fp_num_t scaled_upper_bound;
520 fp_num_t delta;
521 fp_num_t val_dist;
522 int scale;
524 calc_scaled_bounds(ieee_val, &scaled_upper_bound,
525 &delta, &val_dist, &scale);
527 int len = gen_dec_digits(scaled_upper_bound, delta, val_dist, scale,
528 buf, buf_size, dec_exponent);
530 assert(len <= MAX_DOUBLE_STR_LEN);
531 return len;
534 /** Generates a fixed number of decimal digits of w_scaled.
536 * double == w_scaled * 10^-scale, where alpha <= w_scaled.e <= gamma
538 * @param w_scaled Scaled number by 10^-scale so that
539 * alpha <= exponent <= gamma
540 * @param scale Decimal scaling of the value to convert (ie w_scaled).
541 * @param signif_d_cnt Maximum number of significant digits to output.
542 * Negative if as many as possible are requested.
543 * @param frac_d_cnt Maximum number of fractional digits to output.
544 * Negative if as many as possible are requested.
545 * Eg. if 2 then 1.234 -> "1.23"; if 2 then 3e-9 -> "0".
546 * @param buf Buffer to store the string representation. Must be large
547 * enough to store all digits and a null terminator. At most
548 * MAX_DOUBLE_STR_LEN digits will be written (not counting
549 * the null terminator).
550 * @param buf_size Size of buf in bytes.
552 * @return Number of digits; negative on failure (eg buffer too small).
554 static int gen_fixed_dec_digits(fp_num_t w_scaled, int scale, int signif_d_cnt,
555 int frac_d_cnt, char *buf, size_t buf_size, int *dec_exponent)
557 /* We'll produce at least one digit and a null terminator. */
558 if (0 == signif_d_cnt || buf_size < 2) {
559 return -1;
563 * The integral part of w_scaled is 5 to 32 bits long while the
564 * remaining fractional part is 59 to 32 bits long because:
565 * -59 == alpha <= w_scaled.e <= gamma == -32
567 * Therefore:
568 * | 5..32 bits | 32..59 bits | == w_scaled == w * 10^scale
569 * | int_part | frac_part |
570 * |0 0 .. 0 1|0 0 .. 0 0| == one == 1.0
571 * | 0 |0 0 .. 0 1| == w_err == 1 * 2^w_scaled.e
573 assert(alpha <= w_scaled.exponent && w_scaled.exponent <= gamma);
574 assert(0 != w_scaled.significand);
577 * Scaling the number being converted by 10^scale introduced
578 * an error of less that 1 ulp. The actual value of w_scaled
579 * could lie anywhere between w_scaled.signif +/- w_err.
580 * Scale the error locally as we scale the fractional part
581 * of w_scaled.
583 uint64_t w_err = 1;
585 /* one is number 1.0 encoded with the same exponent as w_scaled */
586 fp_num_t one;
587 one.significand = ((uint64_t) 1) << (-w_scaled.exponent);
588 one.exponent = w_scaled.exponent;
590 /* Extract the integral part of w_scaled.
591 w_scaled / one == w_scaled >> -one.e */
592 uint32_t int_part = (uint32_t)(w_scaled.significand >> (-one.exponent));
594 /* Fractional part of w_scaled.
595 w_scaled % one == w_scaled & (one.f - 1) */
596 uint64_t frac_part = w_scaled.significand & (one.significand - 1);
598 size_t len = 0;
600 * The integral part of w_scaled has at least 5 bits (64 + alpha = 5)
601 * and at most 32 bits (64 + gamma = 32). The integral part has
602 * at most 10 decimal digits, so kappa <= 10.
604 int kappa = 10;
605 uint32_t div = 1000000000;
607 int rem_signif_d_cnt = signif_d_cnt;
608 int rem_frac_d_cnt =
609 (frac_d_cnt >= 0) ? (kappa - scale + frac_d_cnt) : INT_MAX;
611 /* Produce decimal digits for the integral part of w_scaled. */
612 while (kappa > 0 && rem_signif_d_cnt != 0 && rem_frac_d_cnt > 0) {
613 int digit = int_part / div;
614 int_part %= div;
616 div /= 10;
617 --kappa;
618 --rem_frac_d_cnt;
620 /* Skip leading zeros. */
621 if (digit == 0 && len == 0) {
622 continue;
625 /* Current length + new digit + null terminator <= buf_size */
626 if (len + 2 <= buf_size) {
627 buf[len] = '0' + digit;
628 ++len;
629 --rem_signif_d_cnt;
630 } else {
631 return -1;
635 /* Generate decimal digits for the fractional part of w_scaled. */
636 while (w_err <= frac_part && rem_signif_d_cnt != 0 && rem_frac_d_cnt > 0) {
638 * Does not overflow because at least 5 upper bits were
639 * taken by the integral part and are now unused in frac_part.
641 frac_part *= 10;
642 w_err *= 10;
644 /* frac_part / one */
645 int digit = (int)(frac_part >> (-one.exponent));
647 /* frac_part %= one */
648 frac_part &= one.significand - 1;
650 --kappa;
651 --rem_frac_d_cnt;
653 /* Skip leading zeros. */
654 if (digit == 0 && len == 0) {
655 continue;
658 /* Current length + new digit + null terminator <= buf_size */
659 if (len + 2 <= buf_size) {
660 buf[len] = '0' + digit;
661 ++len;
662 --rem_signif_d_cnt;
663 } else {
664 return -1;
668 assert(/* 0 <= len && */ len < buf_size);
670 if (0 < len) {
671 *dec_exponent = kappa - scale;
672 assert(frac_d_cnt < 0 || -frac_d_cnt <= *dec_exponent);
673 } else {
675 * The number of fractional digits was too limiting to produce
676 * any digits.
678 assert(rem_frac_d_cnt <= 0 || w_scaled.significand == 0);
679 *dec_exponent = 0;
680 buf[0] = '0';
681 len = 1;
684 if (len < buf_size) {
685 buf[len] = '\0';
686 assert(signif_d_cnt < 0 || (int)len <= signif_d_cnt);
687 return len;
688 } else {
689 return -1;
694 /** Converts a non-special double into its string representation.
696 * Conceptually, the truncated double value is: buf * 10^dec_exponent
698 * Conversion errors are tracked, so all produced digits except the
699 * last one are accurate. Garbage digits are never produced.
700 * If the requested number of digits cannot be produced accurately
701 * due to conversion errors less digits are produced than requested
702 * and the last digit has an error of +/- 1 (so if '7' is the last
703 * converted digit it might have been converted to any of '6'..'8'
704 * had the conversion been completely precise).
706 * If no error occurs at least one digit is output.
708 * The conversion stops once the requested number of significant or
709 * fractional digits is reached or the conversion error is too large
710 * to generate any more digits (whichever happens first).
712 * Any digits following the first (most-significant) digit (this digit
713 * included) are counted as significant digits; eg:
714 * 1.4, 4 signif -> "1400" * 10^-3, ie 1.400
715 * 1000.3, 1 signif -> "1" * 10^3 ie 1000
716 * 0.003, 2 signif -> "30" * 10^-4 ie 0.003
717 * 9.5 1 signif -> "9" * 10^0, ie 9
719 * Any digits following the decimal point are counted as fractional digits.
720 * This includes the zeros that would appear between the decimal point
721 * and the first non-zero fractional digit. If fewer fractional digits
722 * are requested than would allow to place the most-significant digit
723 * a "0" is output. Eg:
724 * 1.4, 3 frac -> "1400" * 10^-3, ie 1.400
725 * 12.34 4 frac -> "123400" * 10^-4, ie 12.3400
726 * 3e-99 4 frac -> "0" * 10^0, ie 0
727 * 0.009 2 frac -> "0" * 10^-2, ie 0
729 * @param ieee_val Binary double description to convert. Must be the product
730 * of extract_ieee_double and it must not be a special number.
731 * @param signif_d_cnt Maximum number of significant digits to produce.
732 * The output is not rounded.
733 * Set to a negative value to generate as many digits
734 * as accurately possible.
735 * @param frac_d_cnt Maximum number of fractional digits to produce including
736 * any zeros immediately trailing the decimal point.
737 * The output is not rounded.
738 * Set to a negative value to generate as many digits
739 * as accurately possible.
740 * @param buf Buffer to store the string representation. Must be large
741 * enough to store all digits and a null terminator. At most
742 * MAX_DOUBLE_STR_LEN digits will be written (not counting
743 * the null terminator).
744 * @param buf_size Size of buf in bytes.
745 * @param dec_exponent Set to the decimal exponent of the number string
746 * in buf.
748 * @return The number of output digits. A negative value indicates
749 * an error: buf too small (or ieee_val.is_special, or
750 * signif_d_cnt == 0).
752 int double_to_fixed_str(ieee_double_t ieee_val, int signif_d_cnt,
753 int frac_d_cnt, char *buf, size_t buf_size, int *dec_exponent)
755 /* The whole computation assumes 64bit significand. */
756 static_assert(sizeof(ieee_val.pos_val.significand) == sizeof(uint64_t));
758 if (ieee_val.is_special) {
759 return -1;
762 /* Zero cannot be normalized. Handle it here. */
763 if (0 == ieee_val.pos_val.significand) {
764 return zero_to_str(buf, buf_size, dec_exponent);
767 /* Normalize and scale. */
768 fp_num_t w = normalize(ieee_val.pos_val);
770 int lower_bin_exp = alpha - w.exponent - significand_width;
772 int scale;
773 fp_num_t scaling_power_of_10;
775 get_power_of_ten(lower_bin_exp, &scaling_power_of_10, &scale);
777 fp_num_t w_scaled = multiply(w, scaling_power_of_10);
779 /* Produce decimal digits from the scaled number. */
780 int len = gen_fixed_dec_digits(w_scaled, scale, signif_d_cnt, frac_d_cnt,
781 buf, buf_size, dec_exponent);
783 assert(len <= MAX_DOUBLE_STR_LEN);
784 return len;