Hello, I am having some problems with a double, is it just me but has anyone noticed when you add 0.8 and 0.9 together, instead of getting 1.7 you get 1.700000020 which comes as a problem when im trying to make it a cost The price in my burger bar is now Regular Burger �1.700000020 hehe Can anyone help me with this. Thank You

If you are dealing with money you can just use ints and treat the values as pennies. So 100 = 1 dollar (or one pound). Then format on output. This avoids all the rounding troubles.

Andy Rayner
Ranch Hand

Joined: Dec 09, 2004
Posts: 36

posted

0

i would do, but the problem is i have to stick to a specification Most of the items are �1.40 or �0.80. Is there any reason why im getting all these remainders? Can i not just have an output of 0.00 cut the rest off? Thanks again for the help

Jeff Allison
Greenhorn

Joined: Dec 09, 2004
Posts: 20

posted

0

i would do, but the problem is i have to stick to a specification Most of the items are �1.40 or �0.80.

Well �1.40 would be 140 and �0.80 would be 80. Add them together and you get 220. Formatted for output that's �2.20. You really can use integers here and just scale by 100.

If you must use doubles, then yes, you can truncate. The reason you're getting rounding errors is that decimal numbers don't always fit precisely into the binary representations used to represent them as floating point numbers.

By way of explanation, let's look at base ten arithmetic that you should have learned in grade school (or whatever you guys call it over in England ). What is 1 / 3? You might say it's 0.3333, but that is only rounded to four decimal places and no longer the exact value of one-third. Binary arithmetic used by a computer suffers from similar problems. Fractional values are subject to round off error when stored in a binary format. If you want more technical details about this, you should google for "IEEE floating point numbers" or something similar. IEEE made the standard that most computers use for storing floating point numbers. There should be plenty of information on the Net about the particular problem you have encountered here. Also, this topic has been discussed previously here, so you may want to use the Search tool to see what has been said about it. If you don't find anything on this particular forum, you may want to try searching "Java In General (intermediate)".

As a rule never use double to represent currency. Decimal values can't be represented exactly by float or double. The solution is to use int, long or BigDecimal [ December 10, 2004: Message edited by: Nigel Browne ]