In (almost no) testing, this handles the digits in the string, on the left side of the decimal point, of your float.
Use at your own risk!
Code:
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
float strToFloat (const char string[])
{
int i,j,lenLeft;
long int n,n2,n3;
float floatValue;
float result = 0.0;
float result2 = 0.0;
int negative = false;
char left[20];
// test for leading minus sign
printf("\nstring: %s\n",string);
if ( string[0] == '-') {
negative = true;
i = 1;
}
else
i=0;
j=0;
while(string[i] != '.') {
if(string[i] != '-') {
left[j++]=string[i];
}
++i;
}
left[j]='\0';
lenLeft=--j;
printf("left: %s lenLeft: %d\n",left,lenLeft);
for(i=0,n=0;i<=lenLeft;i++) {
n2=0;
n3=pow(10,lenLeft-i);
n2+=((left[i]-'0') *n3);
n+=n2;
}
if(negative)
n*=-1;
printf("**n: %ld\n",n);
return 0;
/*
// for converting after the decimal point
if (string[i] == '.')
while ((string[i] >= '0' && string[i] <= '9') || string[i] == '.')
{
if (string[i] == '.')
i++;
else
j = 1;
floatValue = string[i] - '0';
result2 += (floatValue / pow(10, j));
i++;
j++;
}
result = result + result2;
if ( negative )
result = -result;
*/
return result;
}
int main (void)
{
float strToFloat (const char string[]);
strToFloat("-987654321.6921");
//printf ("%f\n", strToFloat("-867.6921"));
return 0;
}