0

Doing the following calculation:

double result = 58/10;

Will result: 5.7999999999999998

I know c++ will round it on further calculations or printing, but I need to compare output with where rounding doesn't occur so I can't have rounding happen because that may just lead to differences in other places in the output.

Is there any way to improve the precision of such calculations and having 58/10 result 5.8?

user207421
  • 305,947
  • 44
  • 307
  • 483
user3917631
  • 119
  • 1
  • 9
  • 3
    I would have thought it would result in 5 because of the integer division. You need to turn at least one of those numeric literals into floating-point, e.g. 58.0/10. – user207421 Jun 06 '22 at 07:33
  • Closely related: https://stackoverflow.com/questions/588004/is-floating-point-math-broken . You may use functionality that stores the value in a way different to `double`; There are libraries doing something like this, but I'm not sure, if any of those work with base 10 though. – fabian Jun 06 '22 at 07:37
  • *I can't have rounding happen* -- This is not a "rounding" issue. Floating point values when represented in binary will not have an exact representation, unless the floating point value is an inverse power of 2 (for example 1/2, 1/4, 1/8, 1/16, etc). If you don't want rounding, don't use `double` (or `float`). Instead, find a fixed-point type, or use a third-party library that has a type that represents decimal fractions exactly. Monetary and financial-based applications many times follow this route. – PaulMcKenzie Jun 06 '22 at 07:44
  • You can try some rational numbers library, such as Boost.Rational. Live demo: https://godbolt.org/z/4vP54a8vM. – Daniel Langr Jun 06 '22 at 08:16
  • 1
    Some alternatives are: use binary coded decimals, use fixed point values, use integer math, use rational numbers, use a big number library. – Eljay Jun 06 '22 at 13:44

1 Answers1

0

5.8 cannot be exactly represented in floating point. If you are working with 2 digits precision after the decimal point, for example if you need to store monetary values, store it as "580" (e.g., 580 cents) and do your own formatting when printing.

printf("%d.%02d", n / 100, n % 100);

Alternatively store the decimal as a fraction:

struct Fraction {
  int numerator;
  int denominator;
};

int main() {
  Fraction f(29, 5);
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93