summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/SNIP/fmtmoney.c
blob: 8d9b1ee3b4b4821567a5eaeeb1afb56e2bbebae4 (plain)
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
114
115
116
117
118
119
/*
**  FMTMONEY.C - Format a U.S. dollar value into a numeric string
**
**  public domain demo by Bob Stout
*/

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

#define Form(s,a) bufptr += sprintf(bufptr, s, a)

static char buf[256], *bufptr;

static char *units[] = {"Zero", "One", "Two", "Three", "Four",
                        "Five", "Six", "Seven", "Eight", "Nine",
                        "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
                        "Fifteen", "Sixteen", "Seventeen", "Eighteen",
                        "Nineteen"},

            *tens[]  = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty",
                        "Seventy", "Eighty", "Ninety"};

static void form_group(int, char *);

/*
**  Call with double amount
**  Rounds cents
**  Returns string in a static buffer
*/

char *fmt_money(double amt)
{
      int temp;
      double dummy, cents = modf(amt, &dummy);

      *buf = '\0';
      bufptr = buf;

      temp = (int)(amt/1E12);
      if (temp)
      {
            form_group(temp, "Trillion");
            amt = fmod(amt, 1E12);
      }

      temp = (int)(amt/1E9);
      if (temp)
      {
            form_group(temp, "Billion");
            amt = fmod(amt, 1E9);
      }

      temp = (int)(amt/1E6);
      if (temp)
      {
            form_group(temp, "Million");
            amt = fmod(amt, 1E6);
      }

      temp = (int)(amt/1E3);
      if (temp)
      {
            form_group(temp, "Thousand");
            amt = fmod(amt, 1E3);
      }
      form_group((int)amt, "");

      if (buf == bufptr)
            Form("%s ", units[0]);

      temp = (int)(cents * 100. + .5);
      sprintf(bufptr, "& %02d/100", temp);

      return buf;
}

/*
**  Process each thousands group
*/

static void form_group(int amt, char *scale)
{
      if (buf != bufptr)
            *bufptr++ = ' ';

      if (100 <= amt)
      {
            Form("%s Hundred ", units[amt/100]);
            amt %= 100;
      }
      if (20 <= amt)
      {
            Form("%s", tens[(amt - 20)/10]);
            if (0 != (amt %= 10))
            {
                  Form("-%s ", units[amt]);
            }
                else    Form("%s", " ");
      }
      else if (amt)
      {
            Form("%s ", units[amt]);
      }

      Form("%s", scale);
}

#ifdef TEST

void main(int argc, char *argv[])
{
      double amt = atof(argv[1]);

      printf("fmt_money(%g) = %s\n", amt, fmt_money(amt));
}

#endif