libcfe  0.12.1
some useful C-functions
char_to_double.c
Go to the documentation of this file.
1 #include "config.h"
2 #include "char_to_double.h"
3 
4 #include <string.h>
5 #include <math.h>
6 
7 #include "len.h"
8 #include "char_to_int.h"
9 
10 #ifndef MIN
11 # define MIN(a, b) (a > b ? b : a)
12 #endif
13 
14 short int check_double(const char *s, int len)
15 {
16  if(s == NULL) return 0;
17  if(len == -1) len = str_len(s);
18 
19  char digits[] = "0123456789";
20  short dot = 1;
21  int i;
22  for(i = 0; i < len; i++)
23  {
24  if(i == 0 && s[i] == '-') continue;
25  if(dot > 0 && s[i] == '.')
26  {
27  dot--;
28  continue;
29  }
30  else if(strchr(digits, s[i]) != NULL)
31  continue;
32  else
33  return 0;
34  }
35  return 1;
36 }
37 
38 long double char_to_double(const char *s, int len)
39 {
40  if(s == NULL) return 0;
41  if(len == -1) len = str_len(s);
42 
43  int k = 1;
44  if(s[0] == '-')
45  {
46  k = -1;
47  s++;
48  len--;
49  }
50 
51  int i = MIN(_len(s, '.'), len);
52  int j = len - i - 1;
53 
54  long double res = char_to_int(s, i, 10);
55  if(j > 0)
56  res += char_to_int(s + i + 1, j, 10) / pow(10, j);
57 
58  return res * k;
59 }
long double char_to_double(const char *s, int len)
int _len(const char *s, char m)
Definition: len.c:8
#define MIN(a, b)
#define str_len(s)
Shorthand for counting '\0' terminating strings. See _len for more info.
Definition: len.h:17
short int check_double(const char *s, int len)
unsigned long long char_to_int(const char *s, int i, uint8_t base)
Definition: char_to_int.c:24