0

Sorry for the long title. Here's the code:

int main()
{
    float d1 = 1.14;
    float d2 = d1 * 100;
    long int l = long int(d2);
    cout << d1 << ", " << d2 << ", " << l << endl;
}

It outputs:

1.14, 114, 113

Why isn't the last value 114? This came up doing an exercise in Stroustrup's Principle's of Programming book (Chapter 9, Exercise 15), where he tells you to have an interface that uses dollars and cents, but to store the value as a long int in a "Money" class. I tested and this doesn't happen with float, only double. It also doesn't happen if you set the d2's value directly to 114. Also note that I'm using Stroustrup's header file, "std_lib_facilities.h"- I hope it's not something in there.

  • This is exactly why if you are working with money, you store it as cents, or whatever precision you actually want. Floating point math is more of an approximation since not all values can be expressed. – NathanOliver May 21 '20 at 13:10
  • 1
    Ask your favorite search engine for *what every programmer should know about floating point numbers*. TLDR: 1.14 cannot be represented exactly in the CPU. It's the same when you write 1/3 down as 0.3333 and then multiply that by 3 -- it gives 0.9999. – j6t May 21 '20 at 13:10

0 Answers0