1 /* uconvert - convert string representations of decimal numbers into whole
2 number/fractional value pairs. */
4 /* Copyright (C) 2008,2009 Free Software Foundation, Inc.
6 This file is part of GNU Bash, the Bourne Again SHell.
8 Bash 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 Bash 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 Bash. If not, see <http://www.gnu.org/licenses/>.
24 #include "bashtypes.h"
26 #if defined (TIME_WITH_SYS_TIME)
27 # include <sys/time.h>
30 # if defined (HAVE_SYS_TIME_H)
31 # include <sys/time.h>
37 #if defined (HAVE_UNISTD_H)
42 #include "chartypes.h"
47 #define DECIMAL '.' /* XXX - should use locale */
51 if (ip) *ip = ipart * mult; \
52 if (up) *up = upart; \
57 * An incredibly simplistic floating point converter.
59 static int multiplier[7] = { 1, 100000, 10000, 1000, 100, 10, 1 };
61 /* Take a decimal number int-part[.[micro-part]] and convert it to the whole
62 and fractional portions. The fractional portion is returned in
63 millionths (micro); callers are responsible for multiplying appropriately.
64 Return 1 if value converted; 0 if invalid integer for either whole or
78 if (s && (*s == '-' || *s == '+'))
80 mult = (*s == '-') ? -1 : 1;
88 if (*p == DECIMAL) /* decimal point */
92 ipart = (ipart * 10) + (*p - '0');
95 if (p == 0 || *p == 0) /* callers ensure p can never be 0; this is to shut up clang */
101 /* Look for up to six digits past a decimal point. */
102 for (n = 0; n < 6 && p[n]; n++)
104 if (DIGIT(p[n]) == 0)
106 upart = (upart * 10) + (p[n] - '0');
109 /* Now convert to millionths */
110 upart *= multiplier[n];
112 if (n == 6 && p[6] >= '5' && p[6] <= '9')
113 upart++; /* round up 1 */