Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ C
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:
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 3-May-12 1:24am
Edited 17-Mar-13 2:34am
v3
Comments
pwasser at 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 at 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 at 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++)
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Try
 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);
 }
  Permalink  
v2
Comments
Fredrik Bornander at 3-May-12 6:44am
   
Beat me by 16 seconds!
Have a +5 :)
CPallini at 3-May-12 6:46am
   
Thank you :-)
Chuck O'Toole at 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 at 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 at 15-Mar-13 20:45pm
   
Great work CPallini!I think really short code for such task!Working perfect.
Also +5.
J.Surjith Kumar at 16-Mar-13 7:57am
   
my 5.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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.
#include <stdio.h>
int  main()
{
    char inputstr[] = "-.45";
    float result= 0.0f;
    int len = sizeof(inputstr)-1;  //Changed size_t to int.
    int dotpos=0;                  //Changed size_t to int.
    int n;      //Changed declaration size_t to int.Moved for support by more compilers.
    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.You could also change int isNegative to char isNegative to save 3 or 1 byte/s depending on your hardware and platform,or bool isNegative if you were in C++,and C is supported by C++,but you might had to change the headers,depending on your compiler.Like <string.h> to <cstring> for example(for GNU GCC compiler).
  Permalink  
v7
Comments
nv3 at 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 at 17-Mar-13 7:10am
   
Ohh :-S Yes you're wright.I meant '-'.I changed it.Thank you.
john_th at 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)

  Print Answers RSS
0 OriginalGriff 245
1 Jochen Arndt 155
2 PIEBALDconsult 150
3 Afzaal Ahmad Zeeshan 120
4 DamithSL 115
0 OriginalGriff 5,695
1 DamithSL 4,591
2 Maciej Los 4,012
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,190


Advertise | Privacy | Mobile
Web03 | 2.8.141220.1 | Last Updated 17 Mar 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100