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

前端 未结 17 2697
孤城傲影
孤城傲影 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:43

    Also, if you're using C++, you can just create a function like this:

    string prd(const double x, const int decDigits) {
        stringstream ss;
        ss << fixed;
        ss.precision(decDigits); // set # places after decimal
        ss << x;
        return ss.str();
    }
    

    You can then output any double myDouble with n places after the decimal point with code such as this:

    std::cout << prd(myDouble,n);
    

提交回复
热议问题