Almost accurate float to string algorithm

On machine 12.341 results in “12.340999”. Close enough eh? Once I get this perfect, I’ll make it into a template function with specifications for making the string in ‘e’ notation.

#include <iostream>
#include <string>
#include <cmath>
#include <cstdio>

std::string ftos(float f, int precis = 6) {
	int e, i;
	std::string buf;
	int whole;
	bool neg;
	
	/* Check for nan or [-]inf */
	if (isnan(f)) return std::string("nan");
	else if (e = isinf(f)) {
		if (e < 0) return std::string("-inf");
		else return std::string("inf");
	}
	
	/* Check for negative and convert to positive */
	if (f < 0) { neg = true; f *= -1.0; }
	
	/* Extract whole number */
	for (whole = 0; f >= 1.0; f -= 1.0, whole++);
	
	/* Convert whole number to string */
	if (neg) buf.push_back('-');
	char tmp[64];
	sprintf(tmp, "%d", whole);
	buf.append(tmp);
	
	if (f == 0.0) return buf;
	buf.push_back('.');
	
	/* Loop through each floating digit in precision */
	for (i = 0; i < precis; i++) {
		if (f == 0.0) break;
		
		/* Shift next floating digit to whole number */
		f *= 10.0;
		/* Extract whole number */
		for (whole = 0; f >= 1.0; f -= 1.0, whole++);
		/* Convert to character */
		buf.push_back(whole + '0');
	}
	
	/* Fill with leading 0's for precision */
	if (f == 0.0 && i < precis)
		for (; i < precis; i++)
			buf.push_back('0');
			
	return buf;
}

int main() {
	std::cout << ftos(12.341) << std::endl;
}

2 thoughts on “Almost accurate float to string algorithm

  1. #include
    #include
    #include
    using namespace std;

    int main(int argc, char* argv[])
    {
    int number[9] = {11,22,33,44,55,66,77,88,99};

    if(argc !=3)
    {
    cout<<"argc = "<<argc;
    cout<<"error in argument \n";
    exit(1);
    }

    ofstream fout1,fout2;

    fout1.open(argv[1]);

    if(fout1.fail())
    {
    cout<<"could not open the file"<<argv[1]<<"\n";
    exit(1);
    }

    fout2.open(argv[2]);

    if(fout2.fail())
    {
    cout<<"could not open the file"<<argv[2]<<"\n";
    exit(1);
    }

    for(int i=0;i<9;i++)
    {
    if(number[i]%2==0)
    fout2<<number[i]<<" ";
    else
    fout1<<number[i]<<" ";
    }

    fout1.close();
    fout2.close();

    ifstream fin;
    char ch;

    for(int i = 1;i<argc;i++)
    {
    fin.open(argv[i]);
    cout<<"content of "<<argv[i]<<"\n";

    do
    {
    fin.get(ch);
    cout<<ch;

    }
    while(fin);

    cout<<"\n\n";
    fin.close();
    }
    }

    it shows error.. send me the solution for this command line argument program. thankyou

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: