samedi 27 mars 2021

How to set format of std::scientific

I want to print 12345.0 as 0.1235e+05. But the below code gives 1.23450e+04. Is there a way to control the format of std::scientific?

#include <iostream>
#include <string>
#include <sstream>


int main()
{
    double a = 12345.0;

    std::stringstream s;

    s.precision(3);

    s << std::scientific;

    s << a;

    std::cout << s.str() << std::endl;

    return 0;
}

The output is

1.235e+04

I also tried the code here Print exponential notation with one leading zero with C++ but there is a problem about rounding. If I set precision to 4 it does not round and gives 0.1234E5 however it should have been 0.1235E5.

Any solution to this?

Aucun commentaire:

Enregistrer un commentaire