C++ 如何在一定数量的小数位后截断浮点数(无四舍五入)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12738892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to truncate a floating point number after a certain number of decimal places (no rounding)?
提问by vhbsouza
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
.
我试图以684.545007
2 点精度打印数字,因为数字在684.54
.
When I use
当我使用
var = 684.545007;
printf("%.2f\n",var);
it outputs 684.55
, but what I'd like to get is 684.54
.
它输出684.55
,但我想得到的是684.54
.
Does anyone knows how can I correct this?
有谁知道我该如何纠正这个问题?
回答by Kerrek SB
What you're looking for is truncation. This should work (at least for numbers that aren't terribly large):
您正在寻找的是truncation。这应该有效(至少对于不是很大的数字):
printf(".2f", ((int)(100 * var)) / 100.0);
The conversion to integer truncates the fractional part.
转换为整数会截断小数部分。
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.
在 C++11 或 C99 中,您可以trunc
为此目的使用专用函数(来自标头<cmath>
或<math.h>
。这将避免对适合整数类型的值的限制。
std::trunc(100 * var) / 100 // no need for casts
回答by Ruslan Yushchenko
Here is my approach. It seems ugly but does work in most cases e.g. var can be larger then int, can be zero or bizarre '-0'. It does not handle infinities and NaNs though.
这是我的方法。它看起来很丑,但在大多数情况下确实有效,例如 var 可以比 int 大,可以为零或奇怪的“-0”。但它不处理无穷大和 NaN。
double var = 684.545007; // or whatever
double var_trunc = var>=0. ? floor(var*100.)/100. : ceil(var*100.)/100.;
printf ("%g\n", var_trunc);
回答by laifjei
printf("%.2f\n", var - 0.005);