14

I' d like to use lexical_cast to convert a float to a string. Usually it works fine, but I have some problems with numbers without decimal. How can I fix number of decimal shown in the string?

Example:

double n=5;
string number;
number = boost::lexical_cast<string>(n);

Result number is 5, I need number 5.00.

Anders
  • 8,307
  • 9
  • 56
  • 88
perusopersonale
  • 896
  • 1
  • 8
  • 18

4 Answers4

31

From the documentation for boost lexical_cast:

For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior of lexical_cast, the conventional stringstream approach is recommended. Where the conversions are numeric to numeric, numeric_cast may offer more reasonable behavior than lexical_cast.

Example:

#include <sstream>
#include <iomanip>

int main() {
    std::ostringstream ss;
    double x = 5;
    ss << std::fixed << std::setprecision(2);
    ss << x;
    std::string s = ss.str();
    return 0;
}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
Mic
  • 6,741
  • 3
  • 24
  • 25
16

Have a look at boost::format library. It merges the usability of printf with type safety of streams. For speed, I do not know, but I doubt it really matters nowadays.

#include <boost/format.hpp>
#include <iostream>

int main()
{
   double x = 5.0;
   std::cout << boost::str(boost::format("%.2f") % x) << '\n';
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Etienne Monette
  • 161
  • 1
  • 3
3

If you need complex formatting, use std::ostringstream instead. boost::lexical_cast is meant for "simple formatting".

std::string
get_formatted_value(double d) {
    std::ostringstream oss;
    oss.setprecision(3);
    oss.setf(std::ostringstream::showpoint);
    oss << d;
    return oss.str();
}
D.Shawley
  • 58,213
  • 10
  • 98
  • 113
1

you can also use sprintf, which is faster then ostringstream

#include <cstdio>
#include <string>

using namespace std;

int main()
{
    double n = 5.0;

    char str_tmp[50];
    sprintf(str_tmp, "%.2f", n); 
    string number(str_tmp);
}
hidayat
  • 9,493
  • 13
  • 51
  • 66