Reputation: 11
This is mine code, not fully finished, and sorry for Polish language but it's easy to get it. http://pastebin.com/QPmVaPFv So, this is about vet, 4 variables are for price per visitor: 1. Big dog 2. Medium dog 3. Small dog 4.cat After that next 4 variables are for numbers of visitor, same as before (big,medium,small,cat etc.)
Then text says: every 5th big dog owner got 10% discount every 3rd medium owner got 50% discount every 4th cat owner got price at 1$ i.e
double zdpies=ldpies/5.;
double zspies=lspies/3.;
double zkot=ckot/4.;
This is that part with discounts
after that i made variables with calculations on discounted price
double cdpiespromo=cdpies/10.; Big dog
double cspiespromo=cspies/50.; medium dog
double ckotpromo=1; Cat
Then i made calculation for final price i.e for normal price without discount
--- cena normalna: 21.6 x 51.0 = 1101.6000000000001
Process completed.
And i got that strange numbers, 51. is ok but 21.6 is wrong that must be 22 not 21.6. When i use "int" it says there is "loss of precision", any ideas how to fix that ?
Here are last variables for calculating final price discounted and without discount.
double idp=ldpies-zdpies; this calculates numbers of visitors without discount
double idc=idp*cdpies; this calculates price number of visitor * normalpriceofbigdog.
Upvotes: 0
Views: 151
Reputation: 85496
Don't use float or double to do financial calculations, use BigDecimal.
Since dealing with BigDecimal is a little cumbersome, I wrote a BdHelper class, to shorten the code necessary for certain operations/conversions. The class is not meant to be complete, I really wrote only the methods that I needed, but you get the idea.
Jon Skeet talked about the pain of using floating point numbers in StackOverflow Dev Days London.
Upvotes: 1
Reputation: 815
There's a great article on using float, double, BigDecimal etc for doing calculation here http://firstclassthoughts.co.uk/java/traps/java_double_traps.html
Bottom line is that there is no perfect solution.
Upvotes: 0
Reputation: 22461
Go With BigDecimal. Here's a good start: Make cents with BigDecimal - JavaWorld.
Upvotes: 0