Printing the correct number of decimal points with cout

前端 未结 12 1621
孤独总比滥情好
孤独总比滥情好 2020-11-22 08:26

I have a list of float values and I want to print them with cout with 2 decimal places.

For example:

10.900  should be prin         


        
12条回答
  •  故里飘歌
    2020-11-22 08:46

    You were nearly there, need to use std::fixed as well, refer http://www.cplusplus.com/reference/iostream/manipulators/fixed/

    #include 
    #include 
    
    int main(int argc, char** argv)
    {
        float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 };
    
        std::cout << std::setprecision(2) << std::fixed;
    
        for(int i = 0; i < 6; ++i)
        {
            std::cout << testme[i] << std::endl;
        }
    
        return 0;
    }
    

    outputs:

    0.12
    1.23
    12.35
    123.45
    1234.50
    12345.00
    

提交回复
热议问题