问题
I want to convert a double to string with fixed width.
If the width is 10, then I want the double value to get round off to this width.
For example, if value = 102.121323435345 and width is 10, then this value should be,
position==> 0123456789 value = 102.121323
I can achieve this with snprintf, but I am looking for a c++ native code to do the same.
char buf[125];
snprint(buf, width, "%.6f", value);
I tried to use the below, but it does not help me much,
std::ostringstream oss;
oss << std::fixed << std::setw(10) << std::precision(6) << value;
std::setw guarantiees the minimum width for the value and if the value is more than the width size, it does not round off the values.
Thanks.
回答1:
You can use osteram::width and ostream::precision function to achieve your goal, like this
std::ostringstream out;
out.width(10);
out.precision(10);
out << 123.12345678910111213;
Although it won't add zeros after the point in order to respect width but it will add spaces (or any character of you choise) before the number. So You'll get ' 102' or '0000000102' (if you call out.fill('0');) instead of '102.000000' if you pass 102 as a input value.
回答2:
How about lexical cast?
double x = 102.1213239999;
std::cout << boost::lexical_cast<std::string>(x).substr(0,10);
Its not exactly what you asked for. I was just trying to think outside the box.
You may also want to look at this question for a discussion on formatting differences between C and C++ and check out the Boost Format Library
回答3:
Is that what you want? Here, we calculate the amount of available precision and set ostream accordingly.
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char* argv[])
{
// Input
double value = 102.1213239999;
// Calculate limits
int digits = ( (value<1) ? 1 : int(1+log10(double(abs(value)))) );
int width = 10;
int precision = (((width-digits-1)>=0) ? (width-digits-1):0);
// Display
cout.setf(ios::fixed);
cout.precision(precision);
cout<<setw(10)<<value<<endl;
return 0;
}
OUTPUT: 102.121324
Btw, if you want a truckload of ways to compute digits, here's how.
来源:https://stackoverflow.com/questions/1496158/convert-double-to-string-with-fixed-width