首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用精度返回双精度

使用精度返回双精度
EN

Stack Overflow用户
提问于 2011-09-11 01:02:19
回答 7查看 11.2K关注 0票数 1

假设我有一个返回double的方法,但我想确定返回值的点之后的精度。我不知道double变量的值。

示例:

代码语言:javascript
复制
double i = 3.365737;
return i;

我希望返回值的精度是点后面的3个数字

含义:返回值为3.365

另一个例子:

代码语言:javascript
复制
double i = 4644.322345;
return i;

我希望返回值是:4644.322

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2011-09-11 01:06:44

您想要的是截断某个数字后面的十进制数字。您可以使用<math.h>中的floor函数轻松完成此操作(如果使用C++,则可以使用<cmath>中的std::floor ):

代码语言:javascript
复制
double TruncateNumber(double In, unsigned int Digits)
{
    double f=pow(10, Digits);
    return ((int)(In*f))/f;
}

尽管如此,我认为在某些情况下,由于浮点内部的工作方式,你可能会得到一些奇怪的结果(最后一位是over/off)。

另一方面,大多数情况下,您只是按原样传递double,仅在将其输出到流中时才截断它,这是使用正确的流标志自动完成的。

票数 6
EN

Stack Overflow用户

发布于 2011-09-11 02:24:05

你将需要小心处理边界情况。任何仅基于pow和强制转换或fmod的实现偶尔都会给出错误的结果,尤其是基于pow(- PRECISION)的实现。

最安全的选择是实现C和C++都不提供的功能:定点算术功能。如果没有这一点,您将需要找到相关边界情况的表示。此问题类似于Excel如何进行舍入的问题。改写我的答案,How does Excel successfully Rounds Floating numbers even though they are imprecise?,来解决这个问题,

代码语言:javascript
复制
// Compute 10 to some positive integral power.
// Dealing with overflow (exponent > 308) is an exercise left to the reader.
double pow10 (unsigned int exponent) {
  double result = 1.0;
  double base = 10.0;
  while (exponent > 0) {
    if ((exponent & 1) != 0) result *= base;
    exponent >>= 1;
    base *= base;
  }
  return result;
}

// Truncate number to some precision.
// Dealing with nonsense such as nplaces=400 is an exercise left to the reader.
double truncate (double x, int nplaces) {
  bool is_neg = false;

  // Things will be easier if we only have to deal with positive numbers.
  if (x < 0.0) {
     is_neg = true;
     x = -x;
  }

  // Construct the supposedly truncated value (round down) and the nearest
  // truncated value above it.
  double round_down, round_up;
  if (nplaces < 0) {
    double scale = pow10 (-nplaces);
    round_down   = std::floor (x / scale);
    round_up     = (round_down + 1.0) * scale;
    round_down  *= scale;
  }
  else {
    double scale = pow10 (nplaces);
    round_down   = std::floor (x * scale);
    round_up     = (round_down + 1.0) / scale;
    round_down  /= scale;
  }

  // Usually the round_down value is the desired value.
  // On rare occasions it is the rounded-up value that is.
  // This is one of those cases where you do want to compare doubles by ==.
  if (x != round_up) x = round_down;

  // Correct the sign if needed.
  if (is_neg) x = -x;

  return x;
}
票数 2
EN

Stack Overflow用户

发布于 2011-09-11 01:08:30

你不能从一个双精度数中“移除”精度。你可以: 4644.322000。这是一个不同的数字,但精度是相同的。

正如@David Heffernan所说,当您将其转换为字符串以进行显示时,请执行此操作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7373205

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档