如何在一定数量的小数位(没有舍入)后截断浮点数?

时间:2022-02-27 16:30:24

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.

我试图以6点精度打印数字684.545007,因为在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?

有谁知道我怎么能纠正这个?

3 个解决方案

#1


23  

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.

转换为整数会截断小数部分。

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(从头文件 。这将避免限制为适合整数类型的值。

std::trunc(100 * var) / 100     // no need for casts

#2


2  

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);

#3


1  

printf("%.2f\n", var - 0.005);

#1


23  

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.

转换为整数会截断小数部分。

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(从头文件 。这将避免限制为适合整数类型的值。

std::trunc(100 * var) / 100     // no need for casts

#2


2  

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);

#3


1  

printf("%.2f\n", var - 0.005);