How to 'cout' the correct number of decimal places of a double value?

前端 未结 9 1814
迷失自我
迷失自我 2020-11-27 07:44

I need help on keeping the precision of a double. If I assign a literal to a double, the actual value was truncated.

int main() {
    double x =         


        
9条回答
  •  再見小時候
    2020-11-27 08:09

    std::cout << std::setprecision(8) << x;
    

    Note that setprecision is persistent and all next floats you print will be printed with that precision, until you change it to a different value. If that's a problem and you want to work around that, you can use a proxy stringstream object:

    std::stringstream s;
    s << std::setprecision(8) << x;
    std::cout << s.str();
    

    For more info on iostream formatting, check out the Input/output manipulators section in cppreference.

提交回复
热议问题