programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# addition and subtraction in double

Ranch Hand
Posts: 45
• Number of slices to send:
Optional 'thank-you' note:

why does the above code return 9999.999999999998.

Is there any way to make it return 10000;

Nischal

Ranch Hand
Posts: 5093
• Number of slices to send:
Optional 'thank-you' note:
no. Floating point arithmetic is limited by the precision of your hardware and cannot be guaranteed to have no difference in far decimal places.
You can of course use Math.round() to turn the result into a long if you so wish but that won't help you in realistic cases where the result is a floating point number of its own.
Another (imo better) option is to use DecimalFormat just for the printing.

This is no restriction of Java btw but of computing hardware in general.

Ranch Hand
Posts: 115
• Number of slices to send:
Optional 'thank-you' note:
its basically because a 1/100 cannot be described in binary as a rational number. A cunning way might be to use BigDecimal - might go horribley wrong tho!

Tom Hill
Ranch Hand
Posts: 115
• Number of slices to send:
Optional 'thank-you' note:
Nice: 9999.999999999998181010596454143524169921875

Nischal Topno
Ranch Hand
Posts: 45
• Number of slices to send:
Optional 'thank-you' note:
The above code is just an illustration. Actually whay my requirment is that there are two amount in double and i need a third double by adding or subtracting the first two.

How can this be achieved.

Nischal

Ranch Hand
Posts: 823
• Number of slices to send:
Optional 'thank-you' note:
Nischal,

If you only have 2 decimal places, e.g. for simple currency calculations, just use the smaller units (i.e. multiply by 100) for calculations and whack the point in for display (various methods). You can get quite a lot of precision out of a long in this way...

The alternative is to take what you're given in the double (it's only inaccurate at the limit of available precision) and round it before displaying.

Jules