Link to home
Start Free TrialLog in
Avatar of yongsing
yongsing

asked on

Convert float to string

How do I convert a float into a string with a precision of 2?

Example:
float x = 1.235;
string s = ? // s contains "1.24" or "1.23", rounding doesn't matter
Avatar of Sys_Prog
Sys_Prog
Flag of India image

#include <iostream>      
#include <sstream>      
#include <iomanip>

using namespace std ;

int main(int argc, char* argv[]){

      float f = 1.234 ;
       ostringstream ostr ;
    ostr << setprecision ( 3 ) << f ;      
    string s ( ostr.str () ) ;
    cout << s  ;
        system("pause");
    return 0;
}



Amit
Avatar of nonubik
nonubik

#include <stdio.h>
...

float f = 1.234;
char sz[12];
sprintf(sz, "%.2f",f); //here the '2' is the precision
Another way
char *s; double x; int i; long l;

s = "  -2309.12E-15";    /* Test of atof */
x = atof( s );
printf( "atof test: \"%s\"; float:  %e\n", s, x );

s = "7.8912654773d210";  /* Test of atof */
x = atof( s );
printf( "atof test: \"%s\"; float:  %e\n", s, x );
Please ignore i gave a solution other way round.

Avatar of yongsing

ASKER

Sys_Prog, your solution doesn't work.

12.225 -> 12
6.444 -> 6.4

I want precision of 2 decimal places:

12.225 -> 12.23
6.444 -> 6.44
ASKER CERTIFIED SOLUTION
Avatar of rstaveley
rstaveley
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
fixed and setprecision(2) works ok, but is there any way to do rounding as well?

16.245 -> 16.24 (your solution)

16.245 -> 16.25 (what I want)

Eh?

--------8<--------
#include <iostream>
#include <iomanip>

int main()
{
      double d = 16.245;
      std::cout << std::fixed;
      for (int precision = 0;precision < 5;precision++)
            std::cout << "Using fixed precision " << precision << " value is " << std::setprecision(precision) << d << '\n';
}
--------8<--------

Using VC7.1 and GC3.2, I get:

Using fixed precision 0 value is 16
Using fixed precision 1 value is 16.2
Using fixed precision 2 value is 16.25
Using fixed precision 3 value is 16.245
Using fixed precision 4 value is 16.2450

That's what you want isn't it?
You can find out what "rounding style" a primitive uses from numeric_limits.

Check this out:
--------8<--------
#include <iostream>
#include <iomanip>
#include <limits>

template<class T> void info(const char *name)
{
        std::cout
                << name
                << std::fixed
                << std::setprecision(3) /* Good enough for the epsilon */
                << " data bits = " << std::numeric_limits<T>::digits
                << " rounding style = " << std::numeric_limits<T>::round_style
                << '\n';
}

#define INFO(T) info<T>(#T)


int main()
{
        INFO(float);
        INFO(double);
        INFO(int);
        INFO(short);
}
--------8<--------

Notice that the floating point numbers have a rounding style of 1, which corresponds to round_to_nearest - see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcstdlib/html/vclrf_limits_Floatroundstyle.asp?frame=true
> /* Good enough for the epsilon */

Stray comment - please ignore
How do you change the rounding style?
> How do you change the rounding style?

It is const, you cannot.

Beware that floating point numbers are stored with error. 16.245 is actually stored as 16.245000000000001 on a 32-bit system.

Let's consider an Kuwaiti financial application. Why Kuwait? Well there are are 1000 fils to the Kuwaiti dinar, which means that we can highlight the problem with the storage of 16.245 dinars:
--------8<--------
#include <iostream>
#include <iomanip>
#include <limits>
#include <cmath>

// Round down the fils
double round_down_fils(double value)
{
      return floor(value*1000)/1000;
}

// Round up the fils
double round_up_fils(double value)
{
      return ceil(value*1000)/1000;
}

int main()
{
      double d;
      std::cout << std::fixed << std::setprecision(3);

      for (;;) {
            std::cout << "Enter a price in dinars and fils: ";
            if (!(std::cin >> d))
                  break;
            std::cout << "     Your price rounds to : " << d << '\n';
            std::cout << "  Your price rounds up to : " << round_up_fils(d) << '\n';
            std::cout << "Your price rounds down to : " << round_down_fils(d) << '\n';
      }
}
--------8<--------

If you enter the price 16.245, you'll find that it rounds up to 16.246 because of the spurious error of 0.000000000000001 in storage.

Rounding up/down floating point numbers needs some careful thought.
OK, never mind, the rounding is not really important to me. Thanks for the helps.