-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathft_atof.c
More file actions
70 lines (63 loc) · 1.74 KB
/
Copy pathft_atof.c
File metadata and controls
70 lines (63 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/******************************************************************************/
/* */
/* ::: :::::::: */
/* ft_atof.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rerodrig <rerodrig@student.42porto.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/03/20 12:10:57 by rerodrig #+# #+# */
/* Updated: 2025/03/20 12:15:08 by rerodrig ### ########.fr */
/* */
/******************************************************************************/
#include "./libft.h"
static double parse_fraction(const char *str, int *i)
{
double fraction;
double result;
fraction = 0.1;
result = 0.0;
if (str[*i] == '.')
{
(*i)++;
while (ft_isdigit(str[*i]))
{
result += fraction * (str[*i] - '0');
fraction *= 0.1;
(*i)++;
}
}
return (result);
}
static double parse_integer(const char *str, int *i)
{
double result;
result = 0.0;
while (ft_isdigit(str[*i]))
{
result = result * 10.0 + (str[*i] - '0');
(*i)++;
}
return (result);
}
double ft_atof(const char *str, char **endptr)
{
int i;
int sign;
double result;
result = 0.0;
sign = 1;
i = 0;
while (ft_isspace(str[i]))
i++;
if (str[i] == '-' || str[i] == '+')
{
if (str[i] == '-')
sign = -1;
i++;
}
result = parse_integer(str, &i);
result += parse_fraction(str, &i);
if (endptr)
*endptr = (char *)&str[i];
return (result * sign);
}