0

How can I check if a double (to 2 decimals) is a multiple of 5??

as we all know the % operator doesn't work on double data types..

and

fmod() doesn't seem to be very reliabe....

what I want to do is check if payment is a multiple of .05.

this is what i am trying with fmod(), where remainder and payment are both doubles

remainder = fmod(payment, 5)

when i use small decimals such as; .05, .10, .15, .20 i get exponential notation even if I use

   cout << setiosflags(ios::showpoint) << setprecision(3) << modulo << "  space   " << payment << endl; 

not sure what I'm doing wrong

Mathew Block
  • 1,613
  • 1
  • 10
  • 9

3 Answers3

3

As you've learned, fmod() isn't being very helpful. This is due to how computers store floating point numbers. See here for more information.

The correct solution here is to choose some integer unit of currency. Real banks might choose .00001 dollars as their integer unit. For you, using .01 dollars as your integer unit is probably sufficient.

This means that if we want to store that a user owes $10.05, we would store that as:

int owed = 1005;

Once you do this, it will be very easy to use % on the number, and it will be very easy to get an accurate result.

Community
  • 1
  • 1
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
-1

What about:

int remainder = ((int)(payment * 100)) % 5

Jonas Wolf
  • 1,154
  • 1
  • 12
  • 20
  • A lot of people will tell you that typecasting is a bad practice, so that's a bit of a sensitive topic here. – Mackiavelli Mar 21 '15 at 19:26
  • 2
    @Mackiavelli: The downvote has very little to do with the cast and very much to do with floating point imprecision. – Bill Lynch Mar 21 '15 at 19:27
-1

As @Angew said, you should never use doubles to represent monetary values. Instead, represent the value as the amount of cents using an integer.

That said, what you should do is to multiply the answer by 100, and then round to the nearest integer and then calculate modulo 5.

I.e.

((int)(payment*100 + 0.5)) % 5
juhist
  • 4,210
  • 16
  • 33