Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hello,

Could you please let me know how to convert string to float without using standard functions, like atoi, atof, strtod, sscanf etc.
My code is:
C++
main()
{
    char inputstr[]="123.45";
    float result= 0.0F;
    float temp;
    int ndecimaldigit,i;

    ndecimaldigit = 1;
    for(i=0;i<=4;i++)
    {
        temp=inputstr[i] - '0';
        ndecimaldigit *= 10;
        temp /= ndecimaldigit;
        result += temp;
    }

    printf("%f %f %d \n",result,temp,ndecimaldigit);
}


But i am getting output as: 0.122671 -0.000129 -31072
which is not correct. I need output as 123.45
Posted
Updated 17-Mar-13 1:34am
v3
Comments
[no name] 3-May-12 6:52am    
This looks like homework. There are glaring errors in your code. It does not seem you have spent enough time trying to solve this before posting.
Write out your algorithm and check against code.
The debugger is your friend.
Chuck O'Toole 3-May-12 18:08pm    
To help your learning, let me offer this one hint as to why you got the answers you got. What do you think this statement will do
temp=inputstr[i] - '0';
When inputstr[i] is a '.' (period) :)
Chuck O'Toole 3-May-12 18:10pm    
Continuing in our education series, how many characters are in inputstr? How many times will this go through the loop?
for(i=0;i<=4;i++)

Try
C++
int  main()
{
  char inputstr[] = "123.45";
  float result= 0.0f;
  size_t len = sizeof(inputstr)-1;
  size_t dotpos = 0;
  for (size_t n = 0; n < len; n++)
  {
    if (inputstr[n] == '.')
    {
      dotpos = len - n  - 1;
    }
    else
    {
      result = result * 10.0f + (inputstr[n]-'0');
    }
  }
  while ( dotpos--)
  {
    result /= 10.0f;
  }
  printf("%f\n",result);
}
 
Share this answer
 
v2
Comments
Fredrik Bornander 3-May-12 6:44am    
Beat me by 16 seconds!
Have a +5 :)
CPallini 3-May-12 6:46am    
Thank you :-)
Chuck O'Toole 3-May-12 10:51am    
Yeah but now he won't learn anything. He'll turn in your code and get a failing grade because it's obviously too advanced for it to be his work. Or worse, the instructor will be impressed and pass him with flying colors and he'll get a job working at your bank's processing department.
CPallini 3-May-12 13:46pm    
Well, you are definitely optimist.
Seriously, my code is not advanced. It is basically the OP one, fixed.
john_th 15-Mar-13 20:45pm    
Great work CPallini!I think really short code for such task!Working perfect.
Also +5.
Quote:
You may also change/add the commented lines below,so that you could support also negative values:
The idea is simply by not touching the great short code CPallini made for positive values and just treat the negative value as positive and multiplying by -1 at the end to make it negative.
C++
#include <stdio.h>
int  main()
{
    char inputstr[] = "-.45";
    float result= 0.0f;
    int len = sizeof(inputstr)-1;
    int dotpos=0;
    int n;
    if (inputstr[0]=='-'||inputstr[0]=='+')   //Added line to check sign.If the number is signed,
        n=1;                 //set n to position 1.
    else                     //(number is not signed)
        n=0;                 //set n to position 0.
/*If the number was signed,then we set n to 1,so that we start with inputstr[1],and at the end if the number was negative we will multiply by -1.*/
    for (; n < len; ++n)         //n is already set to the position of the fisrt number.
        if (inputstr[n] == '.')
            dotpos = len - n  - 1;
        else
            result = result * 10.0f + (inputstr[n]-'0');
    while (dotpos--)
        result /= 10.0f;
    if (inputstr[0]=='-')  //If inputstr[] is "negative",
        result*=(-1);      //multiply the number by -1,making it also negative.
    printf("%f\n",result);
    return 0;
}

I have changed size_t to integer,because I don't know how to use them.
 
Share this answer
 
v8
Comments
nv3 16-Mar-13 5:38am    
John, you might want to improve your code a little. When the string starts with anything else than a '0', you will treat it as negative! If you do sign recognition at the start then simply store the findings in a separate variable and use that at the end as multiplier. Also: What if the string starts with a '+' sign ;-)
john_th 17-Mar-13 7:10am    
Ohh :-S Yes you're wright.I meant '-'.I changed it.Thank you.
john_th 17-Mar-13 7:26am    
You are also wright about the '+' sign and I implemented it this way because my idea while coding this was that only you would want to change a float to char* so you knew that you would never have anything else in there except digits,a dot(or not)and maybe a '-' at the first position.And you would knew because of the way you would have implemented the char* to float function.Otherwise,why would you want to input as char* a float from the user?Input it as float and then convert it «safely» to char*.You would have converted the float to char without a '+'.Or that is what I thought.If for example you where «reading» numbers from a numerical equation,then you would have treat the '+' as addition.That was what I thinked of, but you are wright.I will also change that.After that I cannot think of anything else to expect for inputstr[].

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900