Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
277 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use std::round() as commented by @Revolver_Ocelot

Using floor(x + 0.5) has cases where it fails:

  1. Negative numbers. Of course code could attempt ceil(x - 0.5) for that.

  2. 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.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...