Convert double to String with fixed width

I want to convert double to a fixed-width string.

If the width is 10, I want the double value to be rounded to that width.

For example, if value = 102.121323435345 and the width is 10, then this value should be

  position ==> 0123456789       
            value = 102.121323

I can achieve this with snprintf, but I'm looking for my own C ++ code to do the same.

char buf[125]; snprint(buf, width, "%.6f", value); 

I tried using below, but it doesn’t help me much,

 std::ostringstream oss; oss &lt&lt std::fixed &lt&lt std::setw(10) &lt&lt std::precision(6) &lt&lt value; 

std :: setw guarantees the minimum width for the value, and if the value is larger than the width, it does not round the value.

Thanks.

+1
source share
3 answers

How about lexical casting?

 double x = 102.1213239999; std::cout << boost::lexical_cast<std::string>(x).substr(0,10); 

This is not what you asked for. I was just trying to think outside the box.
You can also view this question to discuss formatting the differences between C and C ++ and check out the Acceleration Format Library

+2
source

You can use osteram :: width and ostream :: precision to achieve your goal like this

 std::ostringstream out; out.width(10); out.precision(10); out << 123.12345678910111213; 

Although it will not add zeros after the dot to respect the width, but it will add spaces (or any character you choose) in front of the number. This way you will get "102" or "0000000102" (if you call out.fill ('0');) instead of "102.000000" if you pass 102 as the input value.

+2
source

Is this what you want? Here we calculate the amount of precision available 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 to find many ways to calculate numbers , here .

+1
source

Source: https://habr.com/ru/post/970129/


All Articles