且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将浮点值限制为 C 中小数点后的两位?

更新时间:2023-09-04 14:53:34

如果你只是想将数字四舍五入输出,那么 "%.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.