Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : Writing doubles in a file with more precision than default

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

like image 545
Andy Avatar asked Dec 12 '22 11:12

Andy


2 Answers

You can use precision function.

like image 132
Alok Save Avatar answered Apr 28 '23 14:04

Alok Save


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.

like image 37
David Hammen Avatar answered Apr 28 '23 12:04

David Hammen