Efficient method for converting a floating point number to string without
any library function
I am working on a code to convert a floating point number to it's
equivalent string. For example if the number is : 2.3456 then the string
should also be 2.3456 (without trailing zeros).
I searched on stackoverflow on these 2 links:
C++ convert floating point number to string
Convert Double/Float to string
but both these are slightly off topic as they tend to ask for
representation in 1eX format or xE+0 format.
This is my attempt:
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
vector<char> V;
string S;
int i=0;
float f=3.14156;
float x=f*1e6;
long long int y=(long long int)(x);
while(y)
{
V.push_back(y%10+'0');
y/=10;
}
reverse(V.begin(),V.end());
for(i=0;i<V.size()-6;i++)
{
S.push_back(V[i]);
}
S.push_back('.');
for(;i<V.size();i++)
S.push_back(V[i]);
i=S.size();
while(i--)
{
if(S[i]=='0')
S.erase(S.begin()+i);
else break;
}
cout<<S<<"\n";
//system("pause");
return 0;
}
Link to ideone: http://ideone.com/Z8wBD7
I want to know how can I efficiently exploit the IEEE 754 floating point
representation standard (using typecesting a char pointer or any other
method) and acheive such a conversion , without using any predefined
library function / scanning from a file.
No comments:
Post a Comment