Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double and stringstream formatting

Tags:

c++

double

double val = 0.1;
std::stringstream ss;
ss << val;
std::string strVal= ss.str();

In the Visual Studio debugger, val has the value 0.10000000000000001 (because 0.1 can't be represented). When val is converted using stringstream, strVal is equal to "0.1". However, when using boost::lexical_cast, the resulting strVal is "0.10000000000000001".

Another example is the following:

double val = 12.12305000012;

Under visual studio val appears as 12.123050000119999, and using stringstream and default precision (6) it becomes 12.1231. I don't really understand why it is not 12.12305(...).

Is there a default precision, or does stringstream have a particular algorithm to convert a double value which can't be exactly represented?

Thanks.

like image 881
Guillaume Paris Avatar asked Oct 15 '12 11:10

Guillaume Paris


People also ask

What is a Stringstream?

The StringStream class in C++ is derived from the iostream class. Similar to other stream-based classes, StringStream in C++ allows performing insertion, extraction, and other operations. It is commonly used in parsing inputs and converting strings to numbers, and vice-versa.

What should I use for Stringstream?

To use stringstream, we need to include sstream header file.

Is Stringstream fast?

stringstreams are primarily there for convenience and type-safety, not speed. The stream will collect the input and then eventually call strtold for the conversion. Makes it hard to be any faster!

How do you declare a Stringstream?

To use stringstream class in the C++ program, we have to use the header <sstream>. For Example, the code to extract an integer from the string would be: string mystr(“2019”); int myInt; stringstream (mystr)>>myInt; Here we declare a string object with value “2019” and an int object “myInt”.


2 Answers

You can change the floating-point precision of a stringstream as follows:

double num = 2.25149;
std::stringstream ss(stringstream::in | stringstream::out);
ss << std::setprecision(5) << num << endl;
ss << std::setprecision(4) << num << endl;

Output:

2.2515
2.251

Note how the numbers are also rounded when appropriate.

like image 159
nickolayratchev Avatar answered Sep 24 '22 18:09

nickolayratchev


For anyone who gets "error: ‘setprecision’ is not a member of ‘std’" you must #include <iomanip> else setprecision(17) will not work!

like image 37
YuZ Avatar answered Sep 23 '22 18:09

YuZ