/* cash_words() * This converts a int4 as well but to a representation using words * Obviously way North American centric - sorry */ Datum cash_words(PG_FUNCTION_ARGS) { Cash value = PG_GETARG_CASH(0); unsigned int val; char buf[256]; char *p = buf; Cash m0; Cash m1; Cash m2; Cash m3; text *result; /* work with positive numbers */ if (value < 0) { value = -value; strcpy(buf, "minus "); p += 6; } else buf[0] = '\0'; /* Now treat as unsigned, to avoid trouble at INT_MIN */ val = (unsigned int) value; m0 = val % 100; /* cents */ m1 = (val / 100) % 1000; /* hundreds */ m2 = (val / 100000) % 1000; /* thousands */ m3 = val / 100000000 % 1000; /* millions */ if (m3) { strcat(buf, num_word(m3)); strcat(buf, " million "); } if (m2) { strcat(buf, num_word(m2)); strcat(buf, " thousand "); } if (m1) strcat(buf, num_word(m1)); if (!*p) strcat(buf, "zero"); strcat(buf, (val / 100) == 1 ? " dollar and " : " dollars and "); strcat(buf, num_word(m0)); strcat(buf, m0 == 1 ? " cent" : " cents"); /* capitalize output */ buf[0] = toupper((unsigned char) buf[0]); /* make a text type for output */ result = (text *) palloc(strlen(buf) + VARHDRSZ); VARATT_SIZEP(result) = strlen(buf) + VARHDRSZ; memcpy(VARDATA(result), buf, strlen(buf)); PG_RETURN_TEXT_P(result); }
/* cash_words() * This converts an int4 as well but to a representation using words * Obviously way North American centric - sorry */ Datum cash_words(PG_FUNCTION_ARGS) { Cash value = PG_GETARG_CASH(0); uint64 val; char buf[256]; char *p = buf; Cash m0; Cash m1; Cash m2; Cash m3; Cash m4; Cash m5; Cash m6; /* work with positive numbers */ if (value < 0) { value = -value; strcpy(buf, "minus "); p += 6; } else buf[0] = '\0'; /* Now treat as unsigned, to avoid trouble at INT_MIN */ val = (uint64) value; m0 = val % INT64CONST(100); /* cents */ m1 = (val / INT64CONST(100)) % 1000; /* hundreds */ m2 = (val / INT64CONST(100000)) % 1000; /* thousands */ m3 = (val / INT64CONST(100000000)) % 1000; /* millions */ m4 = (val / INT64CONST(100000000000)) % 1000; /* billions */ m5 = (val / INT64CONST(100000000000000)) % 1000; /* trillions */ m6 = (val / INT64CONST(100000000000000000)) % 1000; /* quadrillions */ if (m6) { strcat(buf, num_word(m6)); strcat(buf, " quadrillion "); } if (m5) { strcat(buf, num_word(m5)); strcat(buf, " trillion "); } if (m4) { strcat(buf, num_word(m4)); strcat(buf, " billion "); } if (m3) { strcat(buf, num_word(m3)); strcat(buf, " million "); } if (m2) { strcat(buf, num_word(m2)); strcat(buf, " thousand "); } if (m1) strcat(buf, num_word(m1)); if (!*p) strcat(buf, "zero"); strcat(buf, (val / 100) == 1 ? " dollar and " : " dollars and "); strcat(buf, num_word(m0)); strcat(buf, m0 == 1 ? " cent" : " cents"); /* capitalize output */ buf[0] = pg_toupper((unsigned char) buf[0]); /* return as text datum */ PG_RETURN_TEXT_P(cstring_to_text(buf)); }