Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert double to String with fixed width

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 &lt&lt std::fixed &lt&lt std::setw(10) &lt&lt std::precision(6) &lt&lt 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.

like image 844
Ganesh M Avatar asked Feb 05 '26 13:02

Ganesh M


2 Answers

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.

like image 196
Serge Avatar answered Feb 07 '26 01:02

Serge


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

like image 25
Martin York Avatar answered Feb 07 '26 01:02

Martin York



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!