How to output with 3 digits after the decimal point with C++ stream?

前端 未结 4 995
悲哀的现实
悲哀的现实 2020-12-15 20:51

Given a variable of float type, how to output it with 3 digits after the decimal point, using iostream in C++?

相关标签:
4条回答
  • 2020-12-15 21:25

    You can get fixed number of fractional digits (and many other things) by using the iomanip header. For example:

    #include <iostream>
    #include <iomanip>
    
    int main() {
        double pi = 3.141592653589;
        std::cout << std::fixed << std::setprecision(2) << pi << '\n';
        return 0;
    }
    

    will output:

    3.14
    

    Note that both fixed and setprecision change the stream permanently so, if you want to localise the effects, you can save the information beforehand and restore it afterwards:

    #include <iostream>
    #include <iomanip>
    
    int main() {
        double pi = 3.141592653589;
    
        std::cout << pi << '\n';
    
        // Save flags/precision.
        std::ios_base::fmtflags oldflags = std::cout.flags();
        std::streamsize oldprecision = std::cout.precision();
    
        std::cout << std::fixed << std::setprecision(2) << pi << '\n';
        std::cout << pi << '\n';
    
        // Restore flags/precision.
        std::cout.flags (oldflags);
        std::cout.precision (oldprecision);
    
        std::cout << pi << '\n';
    
        return 0;
    }
    

    The output of that is:

    3.14159
    3.14
    3.14
    3.14159
    
    0 讨论(0)
  • 2020-12-15 21:45

    Use setf and precision.

    #include <iostream>
    
    using namespace std;
    
    int main () {
        double f = 3.14159;
        cout.setf(ios::fixed,ios::floatfield);
        cout.precision(3);
        cout << f << endl;
        return 0;
    }
    

    This prints 3.142

    0 讨论(0)
  • 2020-12-15 21:46

    This one does show "13.141"

    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main(){
        double f = 13.14159;
        cout << fixed;
        cout << setprecision(3) << f << endl;
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-15 21:51

    If you want to print numbers with precision of 3 digits after decimal, just add the following thing before printing the number cout << std::setprecision(3) << desired_number. Don't forget to add #include <iomanip> in your code.

    0 讨论(0)
提交回复
热议问题