File: double_to_string.c

package info (click to toggle)
scheme48 1.8%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 14,980 kB
  • ctags: 14,127
  • sloc: lisp: 76,272; ansic: 71,514; sh: 3,026; makefile: 637
file content (113 lines) | stat: -rw-r--r-- 1,949 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/* Copyright (c) 1993-2008 by Richard Kelsey and Jonathan Rees.
   See file COPYING. */

#include <stdlib.h>
#include <string.h>

extern int s48_dragon(char *buf, double v);
extern void s48_free_init(void);

size_t
s48_double_to_string(char *dest, double v)
{
  char raw[33];
  char *buf = dest;
  char *digits = raw;
  int exponent = s48_dragon(raw, v);
  
  int digit_count = strlen(raw);

  if (*digits == '#') /* infinity or NaN */
    {
      strcpy(dest, digits);
      return digit_count;
    }

  if (*digits == '-')
    {
      *buf++ = '-';
      ++digits;
      --digit_count;
    }

  if ((exponent <= -4) || (exponent > (digit_count + 7)))
    /* print with explicit exponent */
    {
      int decimal_point = exponent;
      *buf++ = *digits++;
      if (*digits)
	{
	  *buf++ = '.';
	  while (*digits)
	    *buf++ = *digits++;
	}

      /* exponent */
      *buf++ = 'e';
      
      if (decimal_point < 0)
	{
	  *buf++ = '-';
	  decimal_point = -decimal_point;
	}
      
      {
	int power_of_10 = 1;
	
	while (decimal_point >= (10*power_of_10))
	  power_of_10 *= 10;
	while (power_of_10 > 0)
	  {
	    int digit = decimal_point / power_of_10;
	    *buf++ = digit + '0';
	    decimal_point -= digit * power_of_10;
	    power_of_10 /= 10;
	  }
      }
      *buf = '\0';
    }
  else if (exponent < 0)
    /* 0.<something> */
    {
      *buf++ = '0';
      *buf++ = '.';
      ++exponent;
      while (exponent < 0)
	{
	  *buf++ = '0';
	  ++exponent;
	}
      while (*digits)
	*buf++ = *digits++;
      *buf = '\0';
    }
  else
    /* <something>.<something> */
    {
      while (*digits)
	{
	  *buf++ = *digits++;
	  if (exponent == 0)
	    *buf++ = '.';
	  --exponent;
	}
      if (exponent >= 0)
	{
	  while (exponent >= 0)
	    {
	      *buf++ = '0';
	      --exponent;
	    }
	  *buf++ = '.';
	  *buf++ = '0';
	}
      else
	{
	  if (exponent == -1)
	    *buf++ = '0';
	}
	  
      *buf = '\0';
    }
  return buf - dest;
}