Created
August 23, 2013 13:16
-
-
Save psych0der/6319244 to your computer and use it in GitHub Desktop.
converting float to string without using library function like sprintf
(naive approach , may lead to anomalies)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <math.h> | |
#define precision 6 //precision for decimal digits | |
int main(int argc, char const *argv[]) | |
{ | |
float f,ff; | |
scanf("%f",&f); | |
ff = f; | |
char str[30]; | |
int a,b,c,k,l=0,m,i=0,j; | |
// check for negetive float | |
if(f<0.0) | |
{ | |
str[i++]='-'; | |
f*=-1; | |
} | |
a=f; // extracting whole number | |
f-=a; // extracting decimal part | |
k = precision; | |
// number of digits in whole number | |
while(k>-1) | |
{ | |
l = pow(10,k); | |
m = a/l; | |
if(m>0) | |
{ | |
break; | |
} | |
k--; | |
} | |
// number of digits in whole number are k+1 | |
/* | |
extracting most significant digit i.e. right most digit , and concatenating to string | |
obtained as quotient by dividing number by 10^k where k = (number of digit -1) | |
*/ | |
for(l=k+1;l>0;l--) | |
{ | |
b = pow(10,l-1); | |
c = a/b; | |
str[i++]=c+48; | |
a%=b; | |
} | |
str[i++] = '.'; | |
/* extracting decimal digits till precision */ | |
for(l=0;l<precision;l++) | |
{ | |
f*=10.0; | |
b = f; | |
str[i++]=b+48; | |
f-=b; | |
} | |
str[i]='\0'; | |
printf("\n orignal printf %f\n",ff); | |
printf("\n float string %s\n",str); | |
return 0; | |
} |
Stumbled upon a corner case which caused my program to crash when trying to convert a float without any assigned decimals.
Does work:
float f = 12345.6;
Does not work:
float f = 12345.0;
This is caused by multiplying with 0 inside this for loop (when I >= 1):
/* extracting decimal digits till precision */
for (l = 0; l < PERCISION; l++)
{
f *= 10.0;
b = f;
str[i++] = b + 48;
f -= b;
}
To fix this, just exit the for loop whenever f == 0 :
/* extracting decimal digits till precision */
for (l = 0; l < PERCISION; l++)
{
f *= 10.0;
b = f;
str[i++] = b + 48;
f -= b;
if (f == 0)
{
break;
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is not working for precision=1 and 0 I edited it and it is working fine.
static void float_to_string(float f,char *str, u8 precision)
{
float ff;
//char str[30];
int a,b,c,k,l=0,m,i=0,j;
//scanf("%f",&f);
ff = f;
k--;
// number of digits in whole number are k+1
}