I want to write doubles to a file but the string cast reduces the precision. Edit : I don't really cast but put the doubles in an ostringstream.
Is there another way than parsing each digit using modulo and division to write the doubles with more precision ?
Edit : My application needs to be portable
Here is my current code :
std::string arraytocsv(double v[], int size) {
std::ostringstream oss;
for (int i = 0; i < size; i++) {
oss << v[i] << ";";
}
oss << std::endl;
return oss.str();
}
I've had the precision() function, it works. Thanks
You can use precision function.
After declaring the string stream alter its behavior:
std::ostringstream oss;
oss.flags (std::ios::scientific);
oss.precision (std::numeric_limits<double>::digits10 + 1);
The first call, oss.flags()
, forces C++ I/O to use scientific notation on this string stream, even on something like pi. Printing numbers smaller in magnitude than 1.0 in fixed notation will lose precision while printing big numbers in fixed notation is extreme overkill.
The second call, oss.precision()
tells C++ I/O how many digits to print after the decimal point. Using digits10+1 tells it to print one superfluous digit; digits10
tells how many digits the system is capable of representing without loss of precision.
You will need to #include because of that std::numeric_limits<double>::digits10
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With