From 7e0f021a9aec35fd8e6725e87e3313b101d26f5e Mon Sep 17 00:00:00 2001 From: Tobias Klauser Date: Sun, 27 Jan 2008 11:37:44 +0100 Subject: Initial import (2.0.2-6) --- reference/C/CONTRIB/SNIP/fmtmoney.c | 119 ++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100755 reference/C/CONTRIB/SNIP/fmtmoney.c (limited to 'reference/C/CONTRIB/SNIP/fmtmoney.c') diff --git a/reference/C/CONTRIB/SNIP/fmtmoney.c b/reference/C/CONTRIB/SNIP/fmtmoney.c new file mode 100755 index 0000000..8d9b1ee --- /dev/null +++ b/reference/C/CONTRIB/SNIP/fmtmoney.c @@ -0,0 +1,119 @@ +/* +** FMTMONEY.C - Format a U.S. dollar value into a numeric string +** +** public domain demo by Bob Stout +*/ + +#include +#include +#include +#include + +#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 -- cgit v1.2.3-54-g00ecf