zava on 08/18/10

# written_amount.c

/ Published in: C

1. // Convert number 'amount' to written English words
2. // In short scale
3. // Requires C99 for uint64_t
4. // Supports large 64-bit integer number up to 18,446,744,073,709,551,615
5.
6. #include <stdio.h>
7. #include <stdlib.h>
8. #include <stdint.h>
9.
10. const char* decades[] = {"", "", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"};
11. const char* digits[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN",
12. "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTTEEN", "NINETEEN"};
13.
14. typedef enum {QUINTILLION, QUADRILLION, TRILLION, BILLION, MILLION, THOUSAND, HUNDRED} Numeral;
15. const char* Numeral_Names[] = {"QUINTILLION", "QUADRILLION", "TRILLION","BILLION", "MILLION", "THOUSAND", "HUNDRED"};
16. const uint64_t Numeral_Values[] = {1000000000000000000, 1000000000000000, 1000000000000, 1000000000, 1000000, 1000, 100};
17.
18. void appendstr(char** pstr, const char* append)
19. {
20. register char c;
21. while (1)
22. {
23. c = *append++;
24. if (c == '') break;
25. *(*pstr)++ = c;
26. }
27. }
28.
29. void write(uint64_t amount, char** pstr)
30. {
31. for (uint64_t n = QUINTILLION; n <= HUNDRED; n++)
32. {
33. if (amount < Numeral_Values[n]) continue;
34.
35. write(amount / Numeral_Values[n], pstr);
36. appendstr(pstr, " ");
37. appendstr(pstr, Numeral_Names[n]);
38. appendstr(pstr, " ");
39. amount %= Numeral_Values[n];
40. }
41.
42. if (amount > 20)
43. {
45. amount %= 10;
46. if (amount != 0) appendstr(pstr, "-"); else return;
47. }
48.
49. appendstr(pstr, digits[amount]);
50. }
51.
52. void written_amount(uint64_t amount, char* buffer)
53. {
54. write(amount, &buffer);
55. *buffer = '';
56. }
57.
58. uint64_t rand64()
59. {
60. // Combin 4 parts of low 16-bit of each random()
61. uint64_t R0 = (uint64_t)random() << 48;
62. uint64_t R1 = (uint64_t)random() << 48 >> 16;
63. uint64_t R2 = (uint64_t)random() << 48 >> 32;
64. uint64_t R3 = (uint64_t)random() << 48 >> 48;
65. return R0 | R1 | R2 | R3;
66. }
67.
68. int main (int argc, char const *argv[])
69. {
70. for (int i=0; i < 20; i++)
71. {
72. uint64_t amount = rand64();
73. amount >>= (20 - i) * 3; // scale numbers
74. char buffer[1024] = { 0 };
75. written_amount(amount, buffer);
76. printf("%20llu = %sn", amount, buffer);
77. }
78. return 0;
79. }