Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: How to Convert From Float to String Without Rounding, Truncation or Padding? [duplicate]

I am facing a problem and unable to resolve it. Need help from gurus. Here is sample code:-

float f=0.01f;
printf("%f",f);

if we check value in variable during debugging f contains '0.0099999998' value and output of printf is 0.010000.

a. Is there any way that we may force the compiler to assign same values to variable of float type?

b. I want to convert float to string/character array. How is it possible that only and only exactly same value be converted to string/character array. I want to make sure that no zeros are padded, no unwanted values are padded, no changes in digits as in above example.

like image 983
Azher Iqbal Avatar asked Jun 18 '09 05:06

Azher Iqbal


2 Answers

It is impossible to accurately represent a base 10 decimal number using base 2 values, except for a very small number of values (such as 0.25). To get what you need, you have to switch from the float/double built-in types to some kind of decimal number package.

like image 193
Mark Ransom Avatar answered Sep 20 '22 07:09

Mark Ransom


You could use boost::lexical_cast in this way:

float blah = 0.01;
string w = boost::lexical_cast<string>( blah );

The variable w will contain the text value 0.00999999978. But I can't see when you really need it.

It is preferred to use boost::format to accurately format a float as an string. The following code shows how to do it:

float blah = 0.01;
string w = str( boost::format("%d") % blah ); // w contains exactly "0.01" now
like image 44
Kirill V. Lyadvinsky Avatar answered Sep 22 '22 07:09

Kirill V. Lyadvinsky