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

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

    ...or you can do it the old-fashioned way without any libraries:

    float a = 37.777779;
    
    int b = a; // b = 37    
    float c = a - b; // c = 0.777779   
    c *= 100; // c = 77.777863   
    int d = c; // d = 77;    
    a = b + d / (float)100; // a = 37.770000;
    

    That of course if you want to remove the extra information from the number.

提交回复
热议问题