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

查看:17
本文介绍了如何将浮点值限制在 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天全站免登陆