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

查看:137
本文介绍了如何将浮点值限制为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.

关于舍入的更多(很多!)更多信息,尤其是关于四舍五入的平局决胜规则,请参见有关舍入的Wikipedia文章

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天全站免登陆