improve of cmpl.
[bush.git] / lib / sh / uconvert.c
blobbd1d975982a898137b8cf36de0eab8e14fcb90e4
1 /* uconvert - convert string representations of decimal numbers into whole
2 number/fractional value pairs. */
4 /* Copyright (C) 2008,2009,2020 Free Software Foundation, Inc.
6 This file is part of GNU Bush, the Bourne Again SHell.
8 Bush is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 Bush is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Bush. If not, see <http://www.gnu.org/licenses/>.
22 #include "config.h"
24 #include "bushtypes.h"
26 #include "posixtime.h"
28 #if defined (HAVE_UNISTD_H)
29 #include <unistd.h>
30 #endif
32 #include <stdio.h>
33 #include "chartypes.h"
35 #include "shell.h"
36 #include "builtins.h"
38 #define DECIMAL '.' /* XXX - should use locale */
40 #define RETURN(x) \
41 do { \
42 if (ip) *ip = ipart * mult; \
43 if (up) *up = upart; \
44 if (ep) *ep = p; \
45 return (x); \
46 } while (0)
49 * An incredibly simplistic floating point converter.
51 static int multiplier[7] = { 1, 100000, 10000, 1000, 100, 10, 1 };
53 /* Take a decimal number int-part[.[micro-part]] and convert it to the whole
54 and fractional portions. The fractional portion is returned in
55 millionths (micro); callers are responsible for multiplying appropriately.
56 EP, if non-null, gets the address of the character where conversion stops.
57 Return 1 if value converted; 0 if invalid integer for either whole or
58 fractional parts. */
59 int
60 uconvert(s, ip, up, ep)
61 char *s;
62 long *ip, *up;
63 char **ep;
65 int n, mult;
66 long ipart, upart;
67 char *p;
69 ipart = upart = 0;
70 mult = 1;
72 if (s && (*s == '-' || *s == '+'))
74 mult = (*s == '-') ? -1 : 1;
75 p = s + 1;
77 else
78 p = s;
80 for ( ; p && *p; p++)
82 if (*p == DECIMAL) /* decimal point */
83 break;
84 if (DIGIT(*p) == 0)
85 RETURN(0);
86 ipart = (ipart * 10) + (*p - '0');
89 if (p == 0 || *p == 0) /* callers ensure p can never be 0; this is to shut up clang */
90 RETURN(1);
92 if (*p == DECIMAL)
93 p++;
95 /* Look for up to six digits past a decimal point. */
96 for (n = 0; n < 6 && p[n]; n++)
98 if (DIGIT(p[n]) == 0)
100 if (ep)
102 upart *= multiplier[n];
103 p += n; /* To set EP */
105 RETURN(0);
107 upart = (upart * 10) + (p[n] - '0');
110 /* Now convert to millionths */
111 upart *= multiplier[n];
113 if (n == 6 && p[6] >= '5' && p[6] <= '9')
114 upart++; /* round up 1 */
116 if (ep)
118 p += n;
119 while (DIGIT(*p))
120 p++;
123 RETURN(1);