Debian Codegraph @

src/backend/utils/adt/cash.c

raw
1 /*
2 * cash.c
3 * Written by D'Arcy J.M. Cain
4 * [email protected]
5 * http://www.druid.net/darcy/
6 *
7 * Functions to allow input and output of money normally but store
8 * and handle it as 64 bit ints
9 *
10 * A slightly modified version of this file and a discussion of the
11 * workings can be found in the book "Software Solutions in C" by
12 * Dale Schumacher, Academic Press, ISBN: 0-12-632360-7 except that
13 * this version handles 64 bit numbers and so can hold values up to
14 * $92,233,720,368,547,758.07.
15 *
16 * src/backend/utils/adt/cash.c
17 */
18
19 #include "postgres.h"
20
21 #include <limits.h>
22 #include <ctype.h>
23 #include <math.h>
24
25 #include "common/int.h"
26 #include "libpq/pqformat.h"
27 #include "utils/builtins.h"
28 #include "utils/cash.h"
29 #include "utils/float.h"
30 #include "utils/numeric.h"
31 #include "utils/pg_locale.h"
32
33
34 /*************************************************************************
35 * Private routines
36 ************************************************************************/
37
38 static void
39 append_num_word(StringInfo buf, Cash value)
40 {
41 static const char *const small[] = {
42 "zero", "one", "two", "three", "four", "five", "six", "seven",
43 "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
44 "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty",
45 "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
46 };
47 const char *const *big = small + 18;
48 int tu = value % 100;
49
50 /* deal with the simple cases first */
51 if (value <= 20)
52 {
53 appendStringInfoString(buf, small[value]);
54 return;
55 }
56
57 /* is it an even multiple of 100? */
58 if (!tu)
59 {
60 appendStringInfo(buf, "%s hundred", small[value / 100]);
61 return;
62 }
63
64 /* more than 99? */
65 if (value > 99)
66 {
67 /* is it an even multiple of 10 other than 10? */
68 if (value % 10 == 0 && tu > 10)
69 appendStringInfo(buf, "%s hundred %s",
70 small[value / 100], big[tu / 10]);
71 else if (tu < 20)
72 appendStringInfo(buf, "%s hundred and %s",
73 small[value / 100], small[tu]);
74 else
75 appendStringInfo(buf, "%s hundred %s %s",
76 small[value / 100], big[tu / 10], small[tu % 10]);
77 }
78 else
79 {
80 /* is it an even multiple of 10 other than 10? */
81 if (value % 10 == 0 && tu > 10)
82 appendStringInfoString(buf, big[tu / 10]);
83 else if (tu < 20)
84 appendStringInfoString(buf, small[tu]);
85 else
86 appendStringInfo(buf, "%s %s", big[tu / 10], small[tu % 10]);
87 }
88 }
89
90 static inline Cash
91 cash_pl_cash(Cash c1, Cash c2)
92 {
93 Cash res;
94
95 if (unlikely(pg_add_s64_overflow(c1, c2, &res)))
96 ereport(ERROR,
97 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
98 errmsg("money out of range")));
99
100 return res;
101 }
102
103 static inline Cash
104 cash_mi_cash(Cash c1, Cash c2)
105 {
106 Cash res;
107
108 if (unlikely(pg_sub_s64_overflow(c1, c2, &res)))
109 ereport(ERROR,
110 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
111 errmsg("money out of range")));
112
113 return res;
114 }
115
116 static inline Cash
117 cash_mul_float8(Cash c, float8 f)
118 {
119 float8 res = rint(float8_mul((float8) c, f));
120
121 if (unlikely(isnan(res) || !FLOAT8_FITS_IN_INT64(res)))
122 ereport(ERROR,
123 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
124 errmsg("money out of range")));
125
126 return (Cash) res;
127 }
128
129 static inline Cash
130 cash_div_float8(Cash c, float8 f)
131 {
132 float8 res = rint(float8_div((float8) c, f));
133
134 if (unlikely(isnan(res) || !FLOAT8_FITS_IN_INT64(res)))
135 ereport(ERROR,
136 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
137 errmsg("money out of range")));
138
139 return (Cash) res;
140 }
141
142 static inline Cash
143 cash_mul_int64(Cash c, int64 i)
144 {
145 Cash res;
146
147 if (unlikely(pg_mul_s64_overflow(c, i, &res)))
148 ereport(ERROR,
149 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
150 errmsg("money out of range")));
151
152 return res;
153 }
154
155 static inline Cash
156 cash_div_int64(Cash c, int64 i)
157 {
158 if (unlikely(i == 0))
159 ereport(ERROR,
160 (errcode(ERRCODE_DIVISION_BY_ZERO),
161 errmsg("division by zero")));
162
163 /*
164 * INT64_MIN / -1 is problematic, since the result can't be represented on
165 * a two's-complement machine. Some machines produce INT64_MIN, some
166 * produce zero, some throw an exception. We can dodge the problem by
167 * recognizing that division by -1 is the same as negation.
168 */
169 if (i == -1)
170 {
171 if (unlikely(c == PG_INT64_MIN))
172 ereport(ERROR,
173 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
174 errmsg("money out of range")));
175 return -c;
176 }
177
178 /* No overflow is possible */
179 return c / i;
180 }
181
182 /* cash_in()
183 * Convert a string to a cash data type.
184 * Format is [$]###[,]###[.##]
185 * Examples: 123.45 $123.45 $123,456.78
186 *
187 */
188 Datum
189 cash_in(PG_FUNCTION_ARGS)
190 {
191 char *str = PG_GETARG_CSTRING(0);
192 Node *escontext = fcinfo->context;
193 Cash result;
194 Cash value = 0;
195 Cash dec = 0;
196 Cash sgn = 1;
197 bool seen_dot = false;
198 const char *s = str;
199 int fpoint;
200 char dsymbol;
201 const char *ssymbol,
202 *psymbol,
203 *nsymbol,
204 *csymbol;
205 struct lconv *lconvert = PGLC_localeconv();
206
207 /*
208 * frac_digits will be CHAR_MAX in some locales, notably C. However, just
209 * testing for == CHAR_MAX is risky, because of compilers like gcc that
210 * "helpfully" let you alter the platform-standard definition of whether
211 * char is signed or not. If we are so unfortunate as to get compiled
212 * with a nonstandard -fsigned-char or -funsigned-char switch, then our
213 * idea of CHAR_MAX will not agree with libc's. The safest course is not
214 * to test for CHAR_MAX at all, but to impose a range check for plausible
215 * frac_digits values.
216 */
217 fpoint = lconvert->frac_digits;
218 if (fpoint < 0 || fpoint > 10)
219 fpoint = 2; /* best guess in this case, I think */
220
221 /* we restrict dsymbol to be a single byte, but not the other symbols */
222 if (*lconvert->mon_decimal_point != '\0' &&
223 lconvert->mon_decimal_point[1] == '\0')
224 dsymbol = *lconvert->mon_decimal_point;
225 else
226 dsymbol = '.';
227 if (*lconvert->mon_thousands_sep != '\0')
228 ssymbol = lconvert->mon_thousands_sep;
229 else /* ssymbol should not equal dsymbol */
230 ssymbol = (dsymbol != ',') ? "," : ".";
231 csymbol = (*lconvert->currency_symbol != '\0') ? lconvert->currency_symbol : "$";
232 psymbol = (*lconvert->positive_sign != '\0') ? lconvert->positive_sign : "+";
233 nsymbol = (*lconvert->negative_sign != '\0') ? lconvert->negative_sign : "-";
234
235 #ifdef CASHDEBUG
236 printf("cashin- precision '%d'; decimal '%c'; thousands '%s'; currency '%s'; positive '%s'; negative '%s'\n",
237 fpoint, dsymbol, ssymbol, csymbol, psymbol, nsymbol);
238 #endif
239
240 /* we need to add all sorts of checking here. For now just */
241 /* strip all leading whitespace and any leading currency symbol */
242 while (isspace((unsigned char) *s))
243 s++;
244 if (strncmp(s, csymbol, strlen(csymbol)) == 0)
245 s += strlen(csymbol);
246 while (isspace((unsigned char) *s))
247 s++;
248
249 #ifdef CASHDEBUG
250 printf("cashin- string is '%s'\n", s);
251 #endif
252
253 /* a leading minus or paren signifies a negative number */
254 /* again, better heuristics needed */
255 /* XXX - doesn't properly check for balanced parens - djmc */
256 if (strncmp(s, nsymbol, strlen(nsymbol)) == 0)
257 {
258 sgn = -1;
259 s += strlen(nsymbol);
260 }
261 else if (*s == '(')
262 {
263 sgn = -1;
264 s++;
265 }
266 else if (strncmp(s, psymbol, strlen(psymbol)) == 0)
267 s += strlen(psymbol);
268
269 #ifdef CASHDEBUG
270 printf("cashin- string is '%s'\n", s);
271 #endif
272
273 /* allow whitespace and currency symbol after the sign, too */
274 while (isspace((unsigned char) *s))
275 s++;
276 if (strncmp(s, csymbol, strlen(csymbol)) == 0)
277 s += strlen(csymbol);
278 while (isspace((unsigned char) *s))
279 s++;
280
281 #ifdef CASHDEBUG
282 printf("cashin- string is '%s'\n", s);
283 #endif
284
285 /*
286 * We accumulate the absolute amount in "value" and then apply the sign at
287 * the end. (The sign can appear before or after the digits, so it would
288 * be more complicated to do otherwise.) Because of the larger range of
289 * negative signed integers, we build "value" in the negative and then
290 * flip the sign at the end, catching most-negative-number overflow if
291 * necessary.
292 */
293
294 for (; *s; s++)
295 {
296 /*
297 * We look for digits as long as we have found less than the required
298 * number of decimal places.
299 */
300 if (isdigit((unsigned char) *s) && (!seen_dot || dec < fpoint))
301 {
302 int8 digit = *s - '0';
303
304 if (pg_mul_s64_overflow(value, 10, &value) ||
305 pg_sub_s64_overflow(value, digit, &value))
306 ereturn(escontext, (Datum) 0,
307 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
308 errmsg("value \"%s\" is out of range for type %s",
309 str, "money")));
310
311 if (seen_dot)
312 dec++;
313 }
314 /* decimal point? then start counting fractions... */
315 else if (*s == dsymbol && !seen_dot)
316 {
317 seen_dot = true;
318 }
319 /* ignore if "thousands" separator, else we're done */
320 else if (strncmp(s, ssymbol, strlen(ssymbol)) == 0)
321 s += strlen(ssymbol) - 1;
322 else
323 break;
324 }
325
326 /* round off if there's another digit */
327 if (isdigit((unsigned char) *s) && *s >= '5')
328 {
329 /* remember we build the value in the negative */
330 if (pg_sub_s64_overflow(value, 1, &value))
331 ereturn(escontext, (Datum) 0,
332 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
333 errmsg("value \"%s\" is out of range for type %s",
334 str, "money")));
335 }
336
337 /* adjust for less than required decimal places */
338 for (; dec < fpoint; dec++)
339 {
340 if (pg_mul_s64_overflow(value, 10, &value))
341 ereturn(escontext, (Datum) 0,
342 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
343 errmsg("value \"%s\" is out of range for type %s",
344 str, "money")));
345 }
346
347 /*
348 * should only be trailing digits followed by whitespace, right paren,
349 * trailing sign, and/or trailing currency symbol
350 */
351 while (isdigit((unsigned char) *s))
352 s++;
353
354 while (*s)
355 {
356 if (isspace((unsigned char) *s) || *s == ')')
357 s++;
358 else if (strncmp(s, nsymbol, strlen(nsymbol)) == 0)
359 {
360 sgn = -1;
361 s += strlen(nsymbol);
362 }
363 else if (strncmp(s, psymbol, strlen(psymbol)) == 0)
364 s += strlen(psymbol);
365 else if (strncmp(s, csymbol, strlen(csymbol)) == 0)
366 s += strlen(csymbol);
367 else
368 ereturn(escontext, (Datum) 0,
369 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
370 errmsg("invalid input syntax for type %s: \"%s\"",
371 "money", str)));
372 }
373
374 /*
375 * If the value is supposed to be positive, flip the sign, but check for
376 * the most negative number.
377 */
378 if (sgn > 0)
379 {
380 if (value == PG_INT64_MIN)
381 ereturn(escontext, (Datum) 0,
382 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
383 errmsg("value \"%s\" is out of range for type %s",
384 str, "money")));
385 result = -value;
386 }
387 else
388 result = value;
389
390 #ifdef CASHDEBUG
391 printf("cashin- result is " INT64_FORMAT "\n", result);
392 #endif
393
394 PG_RETURN_CASH(result);
395 }
396
397
398 /* cash_out()
399 * Function to convert cash to a dollars and cents representation, using
400 * the lc_monetary locale's formatting.
401 */
402 Datum
403 cash_out(PG_FUNCTION_ARGS)
404 {
405 Cash value = PG_GETARG_CASH(0);
406 uint64 uvalue;
407 char *result;
408 char buf[128];
409 char *bufptr;
410 int digit_pos;
411 int points,
412 mon_group;
413 char dsymbol;
414 const char *ssymbol,
415 *csymbol,
416 *signsymbol;
417 char sign_posn,
418 cs_precedes,
419 sep_by_space;
420 struct lconv *lconvert = PGLC_localeconv();
421
422 /* see comments about frac_digits in cash_in() */
423 points = lconvert->frac_digits;
424 if (points < 0 || points > 10)
425 points = 2; /* best guess in this case, I think */
426
427 /*
428 * As with frac_digits, must apply a range check to mon_grouping to avoid
429 * being fooled by variant CHAR_MAX values.
430 */
431 mon_group = *lconvert->mon_grouping;
432 if (mon_group <= 0 || mon_group > 6)
433 mon_group = 3;
434
435 /* we restrict dsymbol to be a single byte, but not the other symbols */
436 if (*lconvert->mon_decimal_point != '\0' &&
437 lconvert->mon_decimal_point[1] == '\0')
438 dsymbol = *lconvert->mon_decimal_point;
439 else
440 dsymbol = '.';
441 if (*lconvert->mon_thousands_sep != '\0')
442 ssymbol = lconvert->mon_thousands_sep;
443 else /* ssymbol should not equal dsymbol */
444 ssymbol = (dsymbol != ',') ? "," : ".";
445 csymbol = (*lconvert->currency_symbol != '\0') ? lconvert->currency_symbol : "$";
446
447 if (value < 0)
448 {
449 /* set up formatting data */
450 signsymbol = (*lconvert->negative_sign != '\0') ? lconvert->negative_sign : "-";
451 sign_posn = lconvert->n_sign_posn;
452 cs_precedes = lconvert->n_cs_precedes;
453 sep_by_space = lconvert->n_sep_by_space;
454 }
455 else
456 {
457 signsymbol = lconvert->positive_sign;
458 sign_posn = lconvert->p_sign_posn;
459 cs_precedes = lconvert->p_cs_precedes;
460 sep_by_space = lconvert->p_sep_by_space;
461 }
462
463 /* make the amount positive for digit-reconstruction loop */
464 uvalue = pg_abs_s64(value);
465
466 /* we build the digits+decimal-point+sep string right-to-left in buf[] */
467 bufptr = buf + sizeof(buf) - 1;
468 *bufptr = '\0';
469
470 /*
471 * Generate digits till there are no non-zero digits left and we emitted
472 * at least one to the left of the decimal point. digit_pos is the
473 * current digit position, with zero as the digit just left of the decimal
474 * point, increasing to the right.
475 */
476 digit_pos = points;
477 do
478 {
479 if (points && digit_pos == 0)
480 {
481 /* insert decimal point, but not if value cannot be fractional */
482 *(--bufptr) = dsymbol;
483 }
484 else if (digit_pos < 0 && (digit_pos % mon_group) == 0)
485 {
486 /* insert thousands sep, but only to left of radix point */
487 bufptr -= strlen(ssymbol);
488 memcpy(bufptr, ssymbol, strlen(ssymbol));
489 }
490
491 *(--bufptr) = (uvalue % 10) + '0';
492 uvalue = uvalue / 10;
493 digit_pos--;
494 } while (uvalue || digit_pos >= 0);
495
496 /*----------
497 * Now, attach currency symbol and sign symbol in the correct order.
498 *
499 * The POSIX spec defines these values controlling this code:
500 *
501 * p/n_sign_posn:
502 * 0 Parentheses enclose the quantity and the currency_symbol.
503 * 1 The sign string precedes the quantity and the currency_symbol.
504 * 2 The sign string succeeds the quantity and the currency_symbol.
505 * 3 The sign string precedes the currency_symbol.
506 * 4 The sign string succeeds the currency_symbol.
507 *
508 * p/n_cs_precedes: 0 means currency symbol after value, else before it.
509 *
510 * p/n_sep_by_space:
511 * 0 No <space> separates the currency symbol and value.
512 * 1 If the currency symbol and sign string are adjacent, a <space>
513 * separates them from the value; otherwise, a <space> separates
514 * the currency symbol from the value.
515 * 2 If the currency symbol and sign string are adjacent, a <space>
516 * separates them; otherwise, a <space> separates the sign string
517 * from the value.
518 *----------
519 */
520 switch (sign_posn)
521 {
522 case 0:
523 if (cs_precedes)
524 result = psprintf("(%s%s%s)",
525 csymbol,
526 (sep_by_space == 1) ? " " : "",
527 bufptr);
528 else
529 result = psprintf("(%s%s%s)",
530 bufptr,
531 (sep_by_space == 1) ? " " : "",
532 csymbol);
533 break;
534 case 1:
535 default:
536 if (cs_precedes)
537 result = psprintf("%s%s%s%s%s",
538 signsymbol,
539 (sep_by_space == 2) ? " " : "",
540 csymbol,
541 (sep_by_space == 1) ? " " : "",
542 bufptr);
543 else
544 result = psprintf("%s%s%s%s%s",
545 signsymbol,
546 (sep_by_space == 2) ? " " : "",
547 bufptr,
548 (sep_by_space == 1) ? " " : "",
549 csymbol);
550 break;
551 case 2:
552 if (cs_precedes)
553 result = psprintf("%s%s%s%s%s",
554 csymbol,
555 (sep_by_space == 1) ? " " : "",
556 bufptr,
557 (sep_by_space == 2) ? " " : "",
558 signsymbol);
559 else
560 result = psprintf("%s%s%s%s%s",
561 bufptr,
562 (sep_by_space == 1) ? " " : "",
563 csymbol,
564 (sep_by_space == 2) ? " " : "",
565 signsymbol);
566 break;
567 case 3:
568 if (cs_precedes)
569 result = psprintf("%s%s%s%s%s",
570 signsymbol,
571 (sep_by_space == 2) ? " " : "",
572 csymbol,
573 (sep_by_space == 1) ? " " : "",
574 bufptr);
575 else
576 result = psprintf("%s%s%s%s%s",
577 bufptr,
578 (sep_by_space == 1) ? " " : "",
579 signsymbol,
580 (sep_by_space == 2) ? " " : "",
581 csymbol);
582 break;
583 case 4:
584 if (cs_precedes)
585 result = psprintf("%s%s%s%s%s",
586 csymbol,
587 (sep_by_space == 2) ? " " : "",
588 signsymbol,
589 (sep_by_space == 1) ? " " : "",
590 bufptr);
591 else
592 result = psprintf("%s%s%s%s%s",
593 bufptr,
594 (sep_by_space == 1) ? " " : "",
595 csymbol,
596 (sep_by_space == 2) ? " " : "",
597 signsymbol);
598 break;
599 }
600
601 PG_RETURN_CSTRING(result);
602 }
603
604 /*
605 * cash_recv - converts external binary format to cash
606 */
607 Datum
608 cash_recv(PG_FUNCTION_ARGS)
609 {
610 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
611
612 PG_RETURN_CASH((Cash) pq_getmsgint64(buf));
613 }
614
615 /*
616 * cash_send - converts cash to binary format
617 */
618 Datum
619 cash_send(PG_FUNCTION_ARGS)
620 {
621 Cash arg1 = PG_GETARG_CASH(0);
622 StringInfoData buf;
623
624 pq_begintypsend(&buf);
625 pq_sendint64(&buf, arg1);
626 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
627 }
628
629 /*
630 * Comparison functions
631 */
632
633 Datum
634 cash_eq(PG_FUNCTION_ARGS)
635 {
636 Cash c1 = PG_GETARG_CASH(0);
637 Cash c2 = PG_GETARG_CASH(1);
638
639 PG_RETURN_BOOL(c1 == c2);
640 }
641
642 Datum
643 cash_ne(PG_FUNCTION_ARGS)
644 {
645 Cash c1 = PG_GETARG_CASH(0);
646 Cash c2 = PG_GETARG_CASH(1);
647
648 PG_RETURN_BOOL(c1 != c2);
649 }
650
651 Datum
652 cash_lt(PG_FUNCTION_ARGS)
653 {
654 Cash c1 = PG_GETARG_CASH(0);
655 Cash c2 = PG_GETARG_CASH(1);
656
657 PG_RETURN_BOOL(c1 < c2);
658 }
659
660 Datum
661 cash_le(PG_FUNCTION_ARGS)
662 {
663 Cash c1 = PG_GETARG_CASH(0);
664 Cash c2 = PG_GETARG_CASH(1);
665
666 PG_RETURN_BOOL(c1 <= c2);
667 }
668
669 Datum
670 cash_gt(PG_FUNCTION_ARGS)
671 {
672 Cash c1 = PG_GETARG_CASH(0);
673 Cash c2 = PG_GETARG_CASH(1);
674
675 PG_RETURN_BOOL(c1 > c2);
676 }
677
678 Datum
679 cash_ge(PG_FUNCTION_ARGS)
680 {
681 Cash c1 = PG_GETARG_CASH(0);
682 Cash c2 = PG_GETARG_CASH(1);
683
684 PG_RETURN_BOOL(c1 >= c2);
685 }
686
687 Datum
688 cash_cmp(PG_FUNCTION_ARGS)
689 {
690 Cash c1 = PG_GETARG_CASH(0);
691 Cash c2 = PG_GETARG_CASH(1);
692
693 if (c1 > c2)
694 PG_RETURN_INT32(1);
695 else if (c1 == c2)
696 PG_RETURN_INT32(0);
697 else
698 PG_RETURN_INT32(-1);
699 }
700
701
702 /* cash_pl()
703 * Add two cash values.
704 */
705 Datum
706 cash_pl(PG_FUNCTION_ARGS)
707 {
708 Cash c1 = PG_GETARG_CASH(0);
709 Cash c2 = PG_GETARG_CASH(1);
710
711 PG_RETURN_CASH(cash_pl_cash(c1, c2));
712 }
713
714
715 /* cash_mi()
716 * Subtract two cash values.
717 */
718 Datum
719 cash_mi(PG_FUNCTION_ARGS)
720 {
721 Cash c1 = PG_GETARG_CASH(0);
722 Cash c2 = PG_GETARG_CASH(1);
723
724 PG_RETURN_CASH(cash_mi_cash(c1, c2));
725 }
726
727
728 /* cash_div_cash()
729 * Divide cash by cash, returning float8.
730 */
731 Datum
732 cash_div_cash(PG_FUNCTION_ARGS)
733 {
734 Cash dividend = PG_GETARG_CASH(0);
735 Cash divisor = PG_GETARG_CASH(1);
736 float8 quotient;
737
738 if (divisor == 0)
739 ereport(ERROR,
740 (errcode(ERRCODE_DIVISION_BY_ZERO),
741 errmsg("division by zero")));
742
743 quotient = (float8) dividend / (float8) divisor;
744 PG_RETURN_FLOAT8(quotient);
745 }
746
747
748 /* cash_mul_flt8()
749 * Multiply cash by float8.
750 */
751 Datum
752 cash_mul_flt8(PG_FUNCTION_ARGS)
753 {
754 Cash c = PG_GETARG_CASH(0);
755 float8 f = PG_GETARG_FLOAT8(1);
756
757 PG_RETURN_CASH(cash_mul_float8(c, f));
758 }
759
760
761 /* flt8_mul_cash()
762 * Multiply float8 by cash.
763 */
764 Datum
765 flt8_mul_cash(PG_FUNCTION_ARGS)
766 {
767 float8 f = PG_GETARG_FLOAT8(0);
768 Cash c = PG_GETARG_CASH(1);
769
770 PG_RETURN_CASH(cash_mul_float8(c, f));
771 }
772
773
774 /* cash_div_flt8()
775 * Divide cash by float8.
776 */
777 Datum
778 cash_div_flt8(PG_FUNCTION_ARGS)
779 {
780 Cash c = PG_GETARG_CASH(0);
781 float8 f = PG_GETARG_FLOAT8(1);
782
783 PG_RETURN_CASH(cash_div_float8(c, f));
784 }
785
786
787 /* cash_mul_flt4()
788 * Multiply cash by float4.
789 */
790 Datum
791 cash_mul_flt4(PG_FUNCTION_ARGS)
792 {
793 Cash c = PG_GETARG_CASH(0);
794 float4 f = PG_GETARG_FLOAT4(1);
795
796 PG_RETURN_CASH(cash_mul_float8(c, (float8) f));
797 }
798
799
800 /* flt4_mul_cash()
801 * Multiply float4 by cash.
802 */
803 Datum
804 flt4_mul_cash(PG_FUNCTION_ARGS)
805 {
806 float4 f = PG_GETARG_FLOAT4(0);
807 Cash c = PG_GETARG_CASH(1);
808
809 PG_RETURN_CASH(cash_mul_float8(c, (float8) f));
810 }
811
812
813 /* cash_div_flt4()
814 * Divide cash by float4.
815 *
816 */
817 Datum
818 cash_div_flt4(PG_FUNCTION_ARGS)
819 {
820 Cash c = PG_GETARG_CASH(0);
821 float4 f = PG_GETARG_FLOAT4(1);
822
823 PG_RETURN_CASH(cash_div_float8(c, (float8) f));
824 }
825
826
827 /* cash_mul_int8()
828 * Multiply cash by int8.
829 */
830 Datum
831 cash_mul_int8(PG_FUNCTION_ARGS)
832 {
833 Cash c = PG_GETARG_CASH(0);
834 int64 i = PG_GETARG_INT64(1);
835
836 PG_RETURN_CASH(cash_mul_int64(c, i));
837 }
838
839
840 /* int8_mul_cash()
841 * Multiply int8 by cash.
842 */
843 Datum
844 int8_mul_cash(PG_FUNCTION_ARGS)
845 {
846 int64 i = PG_GETARG_INT64(0);
847 Cash c = PG_GETARG_CASH(1);
848
849 PG_RETURN_CASH(cash_mul_int64(c, i));
850 }
851
852 /* cash_div_int8()
853 * Divide cash by 8-byte integer.
854 */
855 Datum
856 cash_div_int8(PG_FUNCTION_ARGS)
857 {
858 Cash c = PG_GETARG_CASH(0);
859 int64 i = PG_GETARG_INT64(1);
860
861 PG_RETURN_CASH(cash_div_int64(c, i));
862 }
863
864
865 /* cash_mul_int4()
866 * Multiply cash by int4.
867 */
868 Datum
869 cash_mul_int4(PG_FUNCTION_ARGS)
870 {
871 Cash c = PG_GETARG_CASH(0);
872 int32 i = PG_GETARG_INT32(1);
873
874 PG_RETURN_CASH(cash_mul_int64(c, (int64) i));
875 }
876
877
878 /* int4_mul_cash()
879 * Multiply int4 by cash.
880 */
881 Datum
882 int4_mul_cash(PG_FUNCTION_ARGS)
883 {
884 int32 i = PG_GETARG_INT32(0);
885 Cash c = PG_GETARG_CASH(1);
886
887 PG_RETURN_CASH(cash_mul_int64(c, (int64) i));
888 }
889
890
891 /* cash_div_int4()
892 * Divide cash by 4-byte integer.
893 *
894 */
895 Datum
896 cash_div_int4(PG_FUNCTION_ARGS)
897 {
898 Cash c = PG_GETARG_CASH(0);
899 int32 i = PG_GETARG_INT32(1);
900
901 PG_RETURN_CASH(cash_div_int64(c, (int64) i));
902 }
903
904
905 /* cash_mul_int2()
906 * Multiply cash by int2.
907 */
908 Datum
909 cash_mul_int2(PG_FUNCTION_ARGS)
910 {
911 Cash c = PG_GETARG_CASH(0);
912 int16 s = PG_GETARG_INT16(1);
913
914 PG_RETURN_CASH(cash_mul_int64(c, (int64) s));
915 }
916
917 /* int2_mul_cash()
918 * Multiply int2 by cash.
919 */
920 Datum
921 int2_mul_cash(PG_FUNCTION_ARGS)
922 {
923 int16 s = PG_GETARG_INT16(0);
924 Cash c = PG_GETARG_CASH(1);
925
926 PG_RETURN_CASH(cash_mul_int64(c, (int64) s));
927 }
928
929 /* cash_div_int2()
930 * Divide cash by int2.
931 *
932 */
933 Datum
934 cash_div_int2(PG_FUNCTION_ARGS)
935 {
936 Cash c = PG_GETARG_CASH(0);
937 int16 s = PG_GETARG_INT16(1);
938
939 PG_RETURN_CASH(cash_div_int64(c, (int64) s));
940 }
941
942 /* cashlarger()
943 * Return larger of two cash values.
944 */
945 Datum
946 cashlarger(PG_FUNCTION_ARGS)
947 {
948 Cash c1 = PG_GETARG_CASH(0);
949 Cash c2 = PG_GETARG_CASH(1);
950 Cash result;
951
952 result = (c1 > c2) ? c1 : c2;
953
954 PG_RETURN_CASH(result);
955 }
956
957 /* cashsmaller()
958 * Return smaller of two cash values.
959 */
960 Datum
961 cashsmaller(PG_FUNCTION_ARGS)
962 {
963 Cash c1 = PG_GETARG_CASH(0);
964 Cash c2 = PG_GETARG_CASH(1);
965 Cash result;
966
967 result = (c1 < c2) ? c1 : c2;
968
969 PG_RETURN_CASH(result);
970 }
971
972 /* cash_words()
973 * This converts an int4 as well but to a representation using words
974 * Obviously way North American centric - sorry
975 */
976 Datum
977 cash_words(PG_FUNCTION_ARGS)
978 {
979 Cash value = PG_GETARG_CASH(0);
980 uint64 val;
981 StringInfoData buf;
982 text *res;
983 Cash dollars;
984 Cash m0;
985 Cash m1;
986 Cash m2;
987 Cash m3;
988 Cash m4;
989 Cash m5;
990 Cash m6;
991
992 initStringInfo(&buf);
993
994 /* work with positive numbers */
995 if (value < 0)
996 {
997 value = -value;
998 appendStringInfoString(&buf, "minus ");
999 }
1000
1001 /* Now treat as unsigned, to avoid trouble at INT_MIN */
1002 val = (uint64) value;
1003
1004 dollars = val / INT64CONST(100);
1005 m0 = val % INT64CONST(100); /* cents */
1006 m1 = (val / INT64CONST(100)) % 1000; /* hundreds */
1007 m2 = (val / INT64CONST(100000)) % 1000; /* thousands */
1008 m3 = (val / INT64CONST(100000000)) % 1000; /* millions */
1009 m4 = (val / INT64CONST(100000000000)) % 1000; /* billions */
1010 m5 = (val / INT64CONST(100000000000000)) % 1000; /* trillions */
1011 m6 = (val / INT64CONST(100000000000000000)) % 1000; /* quadrillions */
1012
1013 if (m6)
1014 {
1015 append_num_word(&buf, m6);
1016 appendStringInfoString(&buf, " quadrillion ");
1017 }
1018
1019 if (m5)
1020 {
1021 append_num_word(&buf, m5);
1022 appendStringInfoString(&buf, " trillion ");
1023 }
1024
1025 if (m4)
1026 {
1027 append_num_word(&buf, m4);
1028 appendStringInfoString(&buf, " billion ");
1029 }
1030
1031 if (m3)
1032 {
1033 append_num_word(&buf, m3);
1034 appendStringInfoString(&buf, " million ");
1035 }
1036
1037 if (m2)
1038 {
1039 append_num_word(&buf, m2);
1040 appendStringInfoString(&buf, " thousand ");
1041 }
1042
1043 if (m1)
1044 append_num_word(&buf, m1);
1045
1046 if (dollars == 0)
1047 appendStringInfoString(&buf, "zero");
1048
1049 appendStringInfoString(&buf, dollars == 1 ? " dollar and " : " dollars and ");
1050 append_num_word(&buf, m0);
1051 appendStringInfoString(&buf, m0 == 1 ? " cent" : " cents");
1052
1053 /* capitalize output */
1054 buf.data[0] = pg_toupper((unsigned char) buf.data[0]);
1055
1056 /* return as text datum */
1057 res = cstring_to_text_with_len(buf.data, buf.len);
1058 pfree(buf.data);
1059 PG_RETURN_TEXT_P(res);
1060 }
1061
1062
1063 /* cash_numeric()
1064 * Convert cash to numeric.
1065 */
1066 Datum
1067 cash_numeric(PG_FUNCTION_ARGS)
1068 {
1069 Cash money = PG_GETARG_CASH(0);
1070 Datum result;
1071 int fpoint;
1072 struct lconv *lconvert = PGLC_localeconv();
1073
1074 /* see comments about frac_digits in cash_in() */
1075 fpoint = lconvert->frac_digits;
1076 if (fpoint < 0 || fpoint > 10)
1077 fpoint = 2;
1078
1079 /* convert the integral money value to numeric */
1080 result = NumericGetDatum(int64_to_numeric(money));
1081
1082 /* scale appropriately, if needed */
1083 if (fpoint > 0)
1084 {
1085 int64 scale;
1086 int i;
1087 Datum numeric_scale;
1088 Datum quotient;
1089
1090 /* compute required scale factor */
1091 scale = 1;
1092 for (i = 0; i < fpoint; i++)
1093 scale *= 10;
1094 numeric_scale = NumericGetDatum(int64_to_numeric(scale));
1095
1096 /*
1097 * Given integral inputs approaching INT64_MAX, select_div_scale()
1098 * might choose a result scale of zero, causing loss of fractional
1099 * digits in the quotient. We can ensure an exact result by setting
1100 * the dscale of either input to be at least as large as the desired
1101 * result scale. numeric_round() will do that for us.
1102 */
1103 numeric_scale = DirectFunctionCall2(numeric_round,
1104 numeric_scale,
1105 Int32GetDatum(fpoint));
1106
1107 /* Now we can safely divide ... */
1108 quotient = DirectFunctionCall2(numeric_div, result, numeric_scale);
1109
1110 /* ... and forcibly round to exactly the intended number of digits */
1111 result = DirectFunctionCall2(numeric_round,
1112 quotient,
1113 Int32GetDatum(fpoint));
1114 }
1115
1116 PG_RETURN_DATUM(result);
1117 }
1118
1119 /* numeric_cash()
1120 * Convert numeric to cash.
1121 */
1122 Datum
1123 numeric_cash(PG_FUNCTION_ARGS)
1124 {
1125 Datum amount = PG_GETARG_DATUM(0);
1126 Cash result;
1127 int fpoint;
1128 int64 scale;
1129 int i;
1130 Datum numeric_scale;
1131 struct lconv *lconvert = PGLC_localeconv();
1132
1133 /* see comments about frac_digits in cash_in() */
1134 fpoint = lconvert->frac_digits;
1135 if (fpoint < 0 || fpoint > 10)
1136 fpoint = 2;
1137
1138 /* compute required scale factor */
1139 scale = 1;
1140 for (i = 0; i < fpoint; i++)
1141 scale *= 10;
1142
1143 /* multiply the input amount by scale factor */
1144 numeric_scale = NumericGetDatum(int64_to_numeric(scale));
1145 amount = DirectFunctionCall2(numeric_mul, amount, numeric_scale);
1146
1147 /* note that numeric_int8 will round to nearest integer for us */
1148 result = DatumGetInt64(DirectFunctionCall1(numeric_int8, amount));
1149
1150 PG_RETURN_CASH(result);
1151 }
1152
1153 /* int4_cash()
1154 * Convert int4 (int) to cash
1155 */
1156 Datum
1157 int4_cash(PG_FUNCTION_ARGS)
1158 {
1159 int32 amount = PG_GETARG_INT32(0);
1160 Cash result;
1161 int fpoint;
1162 int64 scale;
1163 int i;
1164 struct lconv *lconvert = PGLC_localeconv();
1165
1166 /* see comments about frac_digits in cash_in() */
1167 fpoint = lconvert->frac_digits;
1168 if (fpoint < 0 || fpoint > 10)
1169 fpoint = 2;
1170
1171 /* compute required scale factor */
1172 scale = 1;
1173 for (i = 0; i < fpoint; i++)
1174 scale *= 10;
1175
1176 /* compute amount * scale, checking for overflow */
1177 result = DatumGetInt64(DirectFunctionCall2(int8mul, Int64GetDatum(amount),
1178 Int64GetDatum(scale)));
1179
1180 PG_RETURN_CASH(result);
1181 }
1182
1183 /* int8_cash()
1184 * Convert int8 (bigint) to cash
1185 */
1186 Datum
1187 int8_cash(PG_FUNCTION_ARGS)
1188 {
1189 int64 amount = PG_GETARG_INT64(0);
1190 Cash result;
1191 int fpoint;
1192 int64 scale;
1193 int i;
1194 struct lconv *lconvert = PGLC_localeconv();
1195
1196 /* see comments about frac_digits in cash_in() */
1197 fpoint = lconvert->frac_digits;
1198 if (fpoint < 0 || fpoint > 10)
1199 fpoint = 2;
1200
1201 /* compute required scale factor */
1202 scale = 1;
1203 for (i = 0; i < fpoint; i++)
1204 scale *= 10;
1205
1206 /* compute amount * scale, checking for overflow */
1207 result = DatumGetInt64(DirectFunctionCall2(int8mul, Int64GetDatum(amount),
1208 Int64GetDatum(scale)));
1209
1210 PG_RETURN_CASH(result);
1211 }