Reputation: 387
I don't know how to convert a string value to double or float. Here is the sample string I am trying to convert: "3.45667"
. I am struggling with the handling of the dot.
I tried this but it is not working:
#include<stdio.h>
int main()
{
char string_array[] = { "3.45667" };
float float_array[20], index = 0;
for(index = 0 ; index < 7 ; index++)
{
if(string_array[index] == '.')
{
printf("dot");
// here, how to add dot to the float_array?
} else
{
float_array = (float)(string_array[index] - '0');
}
}
return 0;
}
How to add a decimal point in the above code? I think this could be done with exponent form but I don't know how to use exponent form.
Upvotes: 0
Views: 3452
Reputation: 36339
The following program just counts how many digits are after the decimal point and scales the result in the end, instead of each digit.
float result = 0.0;
float scale = 0.0;
char *s = "3.14567":
while (*s) {
if (*s >= '0' && *s <= '9') {
result = 10.0 * result + (float)(*s - '0');
scale *= 10.0;
}
else if (*s == '.') scale = 1.0;
else { /* ERROR HANDLING */ }
s++;
}
result = result / (scale == 0.0 ? 1.0 : scale)
Upvotes: 0
Reputation: 103824
This works in a pinch:
#include <ctype.h>
double _atof(char *s)
{
double a = 0.0;
int e = 0;
int c;
while ((c = *s++) != '\0' && isdigit(c)) {
a = a*10.0 + (c - '0');
}
if (c == '.') {
while ((c = *s++) != '\0' && isdigit(c)) {
a = a*10.0 + (c - '0');
e = e-1;
}
}
if (c == 'e' || c == 'E') {
int sign = 1;
int i = 0;
c = *s++;
if (c == '+')
c = *s++;
else if (c == '-') {
c = *s++;
sign = -1;
}
while (isdigit(c)) {
i = i*10 + (c - '0');
c = *s++;
}
e += i*sign;
}
while (e > 0) {
a *= 10.0;
e--;
}
while (e < 0) {
a *= 0.1;
e++;
}
return a;
}
You will have a double and then you will need to convert or cast to a float.
Upvotes: 0
Reputation: 9424
int num = 0;
// parse the numbers before the dot
while(*string != '.')
num += 10*num + *string++ - '0';
string++;
float frac = 0.0f;
float div = 1.0f;
// parse the numbers after the dot
while(*string != '\0') {
frac += (*string++ - '0')/div;
div /= 10.0f;
}
float res = num + frac;
or something like this.. most probably some bugs in it..
Upvotes: 0
Reputation: 28302
Use the position of the decimal point in the string to scale the digits by the appropriate factor of 10 when you go to sum them... so the nth item to the left of the decimal is scaled by 10^(n-1) and the mth item to the right is scaled by (0.1)^m. So...
for each char in thestr do
if it's a digit then
Add the digit to the list
else then
dp = position - 1
sum = 0
for each digit in list
sum = sum + digit * pow(10, dp - position)
return sum
Upvotes: 0
Reputation: 33655
Here is an algorithm..
.
EDIT: if not using a C
function, and given the c++ tag, I'd go with..
std::istringstream foo("3.141");
double v;
foo >> v;
No C
function in sight! ;)
Upvotes: 2