Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / January 2006

Tip: Looking for answers? Try searching our database.

.98 cents instead of .99

Thread view: 
joshdalrymple2000@yahoo.com - 29 Jan 2006 22:25 GMT
double totalCost = 3.91, amountPaid = 4.00;
int totalChange;

totalChange = (int)((amountPaid - totalCost) * 100);
System.out.println(totalChange);

it keeps saying the answer is 8... can any one help?
Stefan Schulz - 30 Jan 2006 11:33 GMT
You have run into a bad case of rounding error. doubles are not exactly
the number you wish to represent, and thus, amountPaid - totalCost may
be a tiny bit less then 9, which gets rounded down to 8 by the int cast.
Googmeister - 30 Jan 2006 13:42 GMT
> double totalCost = 3.91, amountPaid = 4.00;
> int totalChange;
[quoted text clipped - 3 lines]
>
> it keeps saying the answer is 8... can any one help?

Try (int) (Math.round(100 * (amountPaid - totalCost)))

Or better use, store the amount as an int/long in pennies
or use BigDecimal to avoid floating point precision issues.
Roedy Green - 30 Jan 2006 14:40 GMT
>Try (int) (Math.round(100 * (amountPaid - totalCost)))
>
>Or better use, store the amount as an int/long in pennies
>or use BigDecimal to avoid floating point precision issues.
for more discussion of the problem of currency calculation see
http://mindprod.com/jgloss/currency.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.