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

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

    Assuming you're talking about round the value for printing, then Andrew Coleson and AraK's answer are correct:

    printf("%.2f", 37.777779);
    

    But note that if you're aiming to round the number to exactly 37.78 for internal use (eg to compare against another value), then this isn't a good idea, due to the way floating point numbers work: you usually don't want to do equality comparisons for floating point, instead use a target value +/- a sigma value. Or encode the number as a string with a known precision, and compare that.

    See the link in Greg Hewgill's answer to a related question, which also covers why you shouldn't use floating point for financial calculations.

提交回复
热议问题