How do I restrict a float value to only two places after the decimal point in C?

前端 未结 17 2700
孤城傲影
孤城傲影 2020-11-22 03:22

How can I round a float value (such as 37.777779) to two decimal places (37.78) in C?

17条回答
  •  感情败类
    2020-11-22 03:50

    In C++ (or in C with C-style casts), you could create the function:

    /* Function to control # of decimal places to be output for x */
    double showDecimals(const double& x, const int& numDecimals) {
        int y=x;
        double z=x-y;
        double m=pow(10,numDecimals);
        double q=z*m;
        double r=round(q);
    
        return static_cast(y)+(1.0/m)*r;
    }
    

    Then std::cout << showDecimals(37.777779,2); would produce: 37.78.

    Obviously you don't really need to create all 5 variables in that function, but I leave them there so you can see the logic. There are probably simpler solutions, but this works well for me--especially since it allows me to adjust the number of digits after the decimal place as I need.

提交回复
热议问题