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

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

    I made this macro for rounding float numbers. Add it in your header / being of file

    #define ROUNDF(f, c) (((float)((int)((f) * (c))) / (c)))
    

    Here is an example:

    float x = ROUNDF(3.141592, 100)
    

    x equals 3.14 :)

提交回复
热议问题