Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

2 Questions 1) Conversion, 2) Use of the modulo/remainder operator

 
David Kaplowitz
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a change making program I'm writing that asks a user for a monetary amount, then it breaks down that amount into smaller values.

So it uses the Scanner class to elicit a double like 99.99. I want it to use 10.00 as it's largest amount and give 9 x 10.00, 1 x 5.00, 4 x 1.00, 3x .25, etc.

So far I have the following:



Where I'm tripping up is in the division. I'm getting back the wrong amount back (9.998999999999999). I want to divide by 10.00 and get the remainder in a separate variable to then be divided by 5.00, etc.

I don't really get how the whole widening conversion thing works, and I _really_ don't get how to use the % operator in this context to divide by 10.00 and get the remainder of 9.99 back into some type of useful variable that I can then divide?

The book I'm reading explains it, but I seem to be too thick to get it to work on my own.

Thanks for any help.

Dave
 
David Kaplowitz
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, I think I stumbled onto most of my answer on my own by making the following changes:

I still don't know how to change the return value of "change = (int) cash / 10;" to just a single digit number instead of a decimal value. So if I divide 90.00 with this program it says my change in tens is 9.00, I just want it to say "9". But that's the least of my worries after having figured out the % thing.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that you should almost never use floating-point (double or float types) for currency calculations. Floating-point is an approximate method of calculation, for values of widely-varying magnitude. When lots of calculations are done using floating-point, significant errors can build up.

For currency, all values have a fairly similar magnitude, and certainly are significant to the same place. Also, exact answers are required.

Currency calculations should almost always be done using integers (int or long types). A common trick is to use an integer to store the value in the smallest unit of the currency (e.g. cents or pence) and do all calculations in those units. Only convert to the larger unit (e.g. dollars, euros, pounds) for final display to the user.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic