Programming Challenge Numbers to Text?
Troy Bowman
troy at dublan.net
Thu May 4 21:10:15 MDT 2006
On May 2, 2006, at 5:54 AM, Steve wrote:
> Hello all,
> This is prolly a little offtopic, but I'm wondering if anyone can
> recommend a good quick method of converting numbers to text.
I suck at C, but here's a stab at it...
troy at azriel:~$ ./count 1 15 100 393 1938 91283 4918239 2147483647
1: one
15: fifteen
100: one hundred
393: three hundred ninety-three
1938: one thousand nine hundred thirty-eight
91283: ninety-one thousand two hundred eighty-three
4918239: four million nine hundred eighteen thousand two hundred
thirty-nine
2147483647: two billion one hundred forty-seven million four hundred
eighty-three thousand six hundred forty-seven
// ------------------------------------
// to compile: gcc -lm -o count count.c
#include <stdio.h>
#include <math.h>
const char *num[13]={"zero","one","two","three","four","five","six",
"seven","eight","nine","ten","eleven","twelve"};
const char *dim[10]={"","teen","twen","thir","for","fif","six","seven",
"eigh","nine"};
const char *pwr[4]={"hundred", "thousand", "million", "billion" };
int main(int argc, char **argv) {
int i;
for (i=1; i < argc; ++i) {
long work = atoi(argv[i]);
char words[256] = "";
stringify(work, words);
printf("%ld: %s\n", work, &words);
}
}
stringify(long work, char *retval) {
if (work > 99) {
long power;
for (power=9; power>-1; power-=3) {
long e = (long)pow(10.0, (double)(power > 0 ? power : 2));
if (work >= e) {
long remainder = work % e;
long coefficient = (work - remainder) / e;
char coefficient_string[256] = "";
char remainder_string[256] = "";
stringify(coefficient, coefficient_string);
if (remainder > 0) stringify(remainder, remainder_string);
sprintf(retval, "%s %s %s", coefficient_string,
pwr[power/3], remainder_string);
break;
}
}
}
else if (work > 19) {
if (work%10 == 0) sprintf(retval, "%sty", dim[work/10]);
else sprintf(retval, "%sty-%s", dim[work/10], num[work%10]);
}
else if (work >12) {
long j = work%10;
sprintf(retval, "%s%s", j==3 || j==5 || j==8 ? dim[j] : num[j],
dim[1]);
}
else sprintf(retval, "%s", num[work]);
}
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2549 bytes
Desc: not available
Url : http://plug.org/pipermail/plug/attachments/20060504/2ffc7bdf/smime.bin
More information about the PLUG
mailing list