Float formatting in C++

后端 未结 5 1538
感情败类
感情败类 2020-12-03 13:59

How do you format a float in C++ to output to two decimal places rounded up? I\'m having no luck with setw and setprecision as my compiler just tel

5条回答
  •  天涯浪人
    2020-12-03 14:34

    If you want the trailing zero from rounding, you can use the C function printf.

    #include 
    #include 
    
    int main() {
        float v = 12.3961;
        std::printf("%.2f",v); //prints 12.40
    }
    

    Compared to:

    #include 
    #include 
    
    int main() {
        float v = 12.3961;
        std::cout << std::setprecision(4) << v; //prints 12.4
    }
    

提交回复
热议问题