如何将浮点值限制为 C 中小数点后的两位? [英] How do I restrict a float value to only two places after the decimal point in C?

查看:22
本文介绍了如何将浮点值限制为 C 中小数点后的两位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C 中将浮点值(例如 37.777779)四舍五入到小数点后两位 (37.78)?

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

推荐答案

如果你只是想将数字四舍五入输出,那么 "%.2f" 格式字符串确实是正确答案.但是,如果您真的想对浮点值进行四舍五入以进行进一步计算,则可以使用以下方法:

If you just want to round the number for output purposes, then the "%.2f" format string is indeed the correct answer. However, if you actually want to round the floating point value for further computation, something like the following works:

#include <math.h>

float val = 37.777779;

float rounded_down = floorf(val * 100) / 100;   /* Result: 37.77 */
float nearest = roundf(val * 100) / 100;  /* Result: 37.78 */
float rounded_up = ceilf(val * 100) / 100;      /* Result: 37.78 */

请注意,您可能需要选择三种不同的四舍五入规则:向下舍入(即截断小数点后两位)、四舍五入到最接近的位置和向上舍入.通常,您希望四舍五入.

Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.

正如其他几个人指出的那样,由于浮点表示的怪癖,这些四舍五入的值可能不完全是明显"的十进制值,但它们会非常接近.

As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.

有关四舍五入的更多(很多!)信息,尤其是四舍五入的平局规则,请参阅 关于舍入的维基百科文章.

For much (much!) more information on rounding, and especially on tie-breaking rules for rounding to nearest, see the Wikipedia article on Rounding.

这篇关于如何将浮点值限制为 C 中小数点后的两位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆