double_to_string.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /* Copyright (c) 1993-2008 by Richard Kelsey and Jonathan Rees.
  2. See file COPYING. */
  3. #include <stdlib.h>
  4. #include <string.h>
  5. extern int s48_dragon(char *buf, double v);
  6. extern void s48_free_init(void);
  7. size_t
  8. s48_double_to_string(char *dest, double v)
  9. {
  10. char raw[33];
  11. char *buf = dest;
  12. char *digits = raw;
  13. int exponent = s48_dragon(raw, v);
  14. int digit_count = strlen(raw);
  15. if (((digits[0] == '+') || (digits[0] == '-'))
  16. && ((digits[1] == 'i') || (digits[1] == 'n')))
  17. /* infinity or NaN */
  18. {
  19. strcpy(dest, digits);
  20. return digit_count;
  21. }
  22. if (*digits == '-')
  23. {
  24. *buf++ = '-';
  25. ++digits;
  26. --digit_count;
  27. }
  28. if ((exponent <= -4) || (exponent > (digit_count + 7)))
  29. /* print with explicit exponent */
  30. {
  31. int decimal_point = exponent;
  32. *buf++ = *digits++;
  33. if (*digits)
  34. {
  35. *buf++ = '.';
  36. while (*digits)
  37. *buf++ = *digits++;
  38. }
  39. /* exponent */
  40. *buf++ = 'e';
  41. if (decimal_point < 0)
  42. {
  43. *buf++ = '-';
  44. decimal_point = -decimal_point;
  45. }
  46. {
  47. int power_of_10 = 1;
  48. while (decimal_point >= (10*power_of_10))
  49. power_of_10 *= 10;
  50. while (power_of_10 > 0)
  51. {
  52. int digit = decimal_point / power_of_10;
  53. *buf++ = digit + '0';
  54. decimal_point -= digit * power_of_10;
  55. power_of_10 /= 10;
  56. }
  57. }
  58. *buf = '\0';
  59. }
  60. else if (exponent < 0)
  61. /* 0.<something> */
  62. {
  63. *buf++ = '0';
  64. *buf++ = '.';
  65. ++exponent;
  66. while (exponent < 0)
  67. {
  68. *buf++ = '0';
  69. ++exponent;
  70. }
  71. while (*digits)
  72. *buf++ = *digits++;
  73. *buf = '\0';
  74. }
  75. else
  76. /* <something>.<something> */
  77. {
  78. while (*digits)
  79. {
  80. *buf++ = *digits++;
  81. if (exponent == 0)
  82. *buf++ = '.';
  83. --exponent;
  84. }
  85. if (exponent >= 0)
  86. {
  87. while (exponent >= 0)
  88. {
  89. *buf++ = '0';
  90. --exponent;
  91. }
  92. *buf++ = '.';
  93. *buf++ = '0';
  94. }
  95. else
  96. {
  97. if (exponent == -1)
  98. *buf++ = '0';
  99. }
  100. *buf = '\0';
  101. }
  102. return buf - dest;
  103. }