toaruos/libc/stdlib/strtod.c

78 lines
1.2 KiB
C
Raw Normal View History

2018-06-25 06:11:33 +03:00
#include <stdlib.h>
2018-06-26 14:53:48 +03:00
#include <math.h>
#include <stdio.h>
2018-06-25 06:11:33 +03:00
double strtod(const char *nptr, char **endptr) {
int sign = 1;
if (*nptr == '-') {
sign = -1;
nptr++;
}
long long decimal_part = 0;
while (*nptr && *nptr != '.') {
if (*nptr < '0' || *nptr > '9') {
2018-06-26 14:53:48 +03:00
break;
2018-06-25 06:11:33 +03:00
}
decimal_part *= 10LL;
decimal_part += (long long)(*nptr - '0');
nptr++;
}
double sub_part = 0;
double multiplier = 0.1;
if (*nptr == '.') {
nptr++;
while (*nptr) {
if (*nptr < '0' || *nptr > '9') {
2018-06-26 14:53:48 +03:00
break;
2018-06-25 06:11:33 +03:00
}
sub_part += multiplier * (*nptr - '0');
multiplier *= 0.1;
nptr++;
}
}
2018-06-26 14:53:48 +03:00
double expn = (double)sign;
if (*nptr == 'e' || *nptr == 'E') {
nptr++;
int exponent_sign = 1;
if (*nptr == '+') {
nptr++;
} else if (*nptr == '-') {
exponent_sign = -1;
nptr++;
}
int exponent = 0;
while (*nptr) {
if (*nptr < '0' || *nptr > '9') {
break;
}
exponent *= 10;
exponent += (*nptr - '0');
nptr++;
}
expn = pow(10.0,(double)(exponent * exponent_sign));
}
2018-06-25 06:11:33 +03:00
if (endptr) {
*endptr = (char *)nptr;
}
2018-06-26 14:53:48 +03:00
double result = ((double)decimal_part + sub_part) * expn;
return result;
2018-06-25 06:11:33 +03:00
}
2018-10-12 04:35:28 +03:00
float strtof(const char *nptr, char **endptr) {
return strtod(nptr,endptr);
}