精确返回双精度 [英] Returning double with precision
问题描述
假设我有一个方法返回一个 double
,但我想确定要返回的值的点之后的精度。我不知道 double
varaible的值。
Say I have a method returning a double
, but I want to determine the precision after the dot of the value to be returned. I don't know the value of the double
varaible.
示例:
double i = 3.365737;
return i;
我希望返回值的精度为3之后的数字
I want the return value to be with precision of 3 number after the dot
含义:返回值 3.365
。
p>
Another example:
double i = 4644.322345;
return i;
我想要的返回值为: 4644.322
推荐答案
你想要的是在某个数字后截断十进制数字。您可以使用< math.h>
(或)的
floor
如果使用C ++,则 cd> cd> cd>
What you want is truncation of decimal digits after a certain digit. You can easily do that with the floor
function from <math.h>
(or std::floor
from <cmath>
if you're using C++):
double TruncateNumber(double In, unsigned int Digits)
{
double f=pow(10, Digits);
return ((int)(In*f))/f;
}
不过,我认为在某些情况下你可能会得到一些奇怪的结果
Still, I think that in some cases you may get some strange results (the last digit being one over/off) due to how floating point internally works.
另一方面,大多数时间,你只是传递 double
,只是在流上输出时截断它,这是使用正确的流标志自动完成。
On the other hand, most of time you just pass around the double
as is and truncate it only when outputting it on a stream, which is done automatically with the right stream flags.
这篇关于精确返回双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!