1 | /* |
2 | * This Source Code Form is subject to the terms of the Mozilla Public |
3 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
4 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. |
5 | * |
6 | * Copyright 1997 - July 2008 CWI, August 2008 - 2019 MonetDB B.V. |
7 | */ |
8 | |
9 | #include "monetdb_config.h" |
10 | |
11 | #include "sql_decimal.h" |
12 | |
13 | #ifdef HAVE_HGE |
14 | hge |
15 | #else |
16 | lng |
17 | #endif |
18 | decimal_from_str(char *dec, char **end) |
19 | { |
20 | #ifdef HAVE_HGE |
21 | hge res = 0; |
22 | const hge max0 = GDK_hge_max / 10, max1 = GDK_hge_max % 10; |
23 | #else |
24 | lng res = 0; |
25 | const lng max0 = GDK_lng_max / 10, max1 = GDK_lng_max % 10; |
26 | #endif |
27 | int neg = 0; |
28 | |
29 | while(isspace((unsigned char) *dec)) |
30 | dec++; |
31 | if (*dec == '-') { |
32 | neg = 1; |
33 | dec++; |
34 | } else if (*dec == '+') { |
35 | dec++; |
36 | } |
37 | for (; *dec && (isdigit((unsigned char) *dec) || *dec == '.'); dec++) { |
38 | if (*dec != '.') { |
39 | if (res > max0 || (res == max0 && *dec - '0' > max1)) |
40 | break; |
41 | res *= 10; |
42 | res += *dec - '0'; |
43 | } |
44 | } |
45 | while(isspace((unsigned char) *dec)) |
46 | dec++; |
47 | if (end) |
48 | *end = dec; |
49 | if (neg) |
50 | return -res; |
51 | else |
52 | return res; |
53 | } |
54 | |
55 | char * |
56 | #ifdef HAVE_HGE |
57 | decimal_to_str(hge v, sql_subtype *t) |
58 | #else |
59 | decimal_to_str(lng v, sql_subtype *t) |
60 | #endif |
61 | { |
62 | char buf[64]; |
63 | int scale = t->scale, cur = 63, neg = (v<0), i, done = 0; |
64 | |
65 | if (v<0) v = -v; |
66 | |
67 | buf[cur--] = 0; |
68 | if (scale){ |
69 | for (i=0; i<scale; i++) { |
70 | buf[cur--] = (char) (v%10 + '0'); |
71 | v /= 10; |
72 | } |
73 | buf[cur--] = '.'; |
74 | } |
75 | while (v) { |
76 | buf[cur--] = (char ) (v%10 + '0'); |
77 | v /= 10; |
78 | done = 1; |
79 | } |
80 | if (!done) |
81 | buf[cur--] = '0'; |
82 | if (neg) |
83 | buf[cur--] = '-'; |
84 | assert(cur >= -1); |
85 | return _STRDUP(buf+cur+1); |
86 | } |
87 | |
88 | |