四舍五入为0.5精度 [英] Rounding float value off with 0.5 accuracy

查看:63
本文介绍了四舍五入为0.5精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将小数点后的单个数字四舍五入到一个小数点,例如给定的18.0-18.4我想显示18.0或给定的18.5-19.0显示19.0等?谢谢大家

How do you go about rounding a float value with lets say a single number after the decimal point off to for example given 18.0-18.4 I would like to display 18.0 or given 18.5-19.0 show 19.0 etc? thanks folks

推荐答案

使用使用 floor(x + 0.5)会导致失败:

  1. 负数.当然,代码可以为此尝试 ceil(x-0.5).

在总和 x + 0.5 可能会产生四舍五入的答案的情况下,该答案是一个新的整数:FP数刚好小于0.5. x 的ULP(最小表示二进制数字)为0.5或1.0的某些值.

Cases where the sum x+0.5 may create a rounded answer that is a new integer: The FP number just less than 0.5. Some values where the ULP (the least signification binary digit) of x is 0.5 or 1.0.

IOW,代码需要确保添加 0.5 并不需要额外的精度.

IOWs, code needs to insure a 0.5 addition does not require extra precision.

下面是应 round()不存在的候选 round_alt(). round_alt()没有这些问题.

Below is a candidate round_alt() should round() not exist. round_alt() does not have these problems.

double round_alt(double x) {
  double ipart;
  // break into integer and fraction parts
  double fpart = modf(x, &ipart);
  if (fpart != 0.0) {
    if (x >= 0.5) {
      ipart += floor(fpart + 0.5);
    } else if (x <= -0.5) {
      ipart += ceil(fpart - 0.5);
    }
  }
  return ipart;
}

这篇关于四舍五入为0.5精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆