如何在一定的小数位数(不四舍五入)后截断浮点数? [英] How to truncate a floating point number after a certain number of decimal places (no rounding)?
问题描述
我要打印的数量 684.545007
2分precision的在这个意义上,这一数字被截断(不四舍五入)在 684.54
。
I'm trying to print the number 684.545007
with 2 points precision in the sense that the number be truncated (not rounded) after 684.54
.
当我使用
var = 684.545007;
printf("%.2f\n",var);
它输出 684.55
,但我希望得到的是 684.54
。
有谁知道我该如何纠正呢?
Does anyone knows how can I correct this?
推荐答案
什么你要找的是的截的。这应该工作(至少对于那些不是非常大的数字):
What you're looking for is truncation. This should work (at least for numbers that aren't terribly large):
printf(".2f", ((int)(100 * var)) / 100.0);
到整数转换截断小数部分。
The conversion to integer truncates the fractional part.
在C ++ 11或C99,可以使用专用的功能 TRUNC
用于此目的(从标题< CMATH>
或<数学。 H>
这将避免的限制是适合整型值
In C++11 or C99, you can use the dedicated function trunc
for this purpose (from the header <cmath>
or <math.h>
. This will avoid the restriction to values that fit into an integral type.
std::trunc(100 * var) / 100 // no need for casts
这篇关于如何在一定的小数位数(不四舍五入)后截断浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!