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/>.
24 #include "bushtypes.h"
26 #include "posixtime.h"
28 #if defined (HAVE_UNISTD_H)
33 #include "chartypes.h"
38 #define DECIMAL '.' /* XXX - should use locale */
42 if (ip) *ip = ipart * mult; \
43 if (up) *up = upart; \
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
60 uconvert(s
, ip
, up
, ep
)
72 if (s
&& (*s
== '-' || *s
== '+'))
74 mult
= (*s
== '-') ? -1 : 1;
82 if (*p
== DECIMAL
) /* decimal point */
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 */
95 /* Look for up to six digits past a decimal point. */
96 for (n
= 0; n
< 6 && p
[n
]; n
++)
102 upart
*= multiplier
[n
];
103 p
+= n
; /* To set EP */
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 */