Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

c++ - Rounding float value off with 0.5 accuracy

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...