> > Check out the following:
> >
[quoted text clipped - 11 lines]
> > displayed is 4.5099998. Can someone please explain why this is happening,
> > and how would I be able to limit the answer to two decimal places.
(Quoted from Patricia) :
On any system, in any language, any data type based on IEEE754 64 bit
binary floating point has 53 bits, about 15.9 decimal digits, of precision.
Just as no decimal fraction can exactly represent 1/3 or 2/3,
so no binary fraction can exactly represent 1/10 or 2/10.
Subtracting numbers of equal magnitude with a matching leading decimal
digit costs a digit of precision, so it should be expected that the result will
be accurate to just under 15 decimal digits.
The unusual thing about Java in this area is the high precision of its default
String conversion for floating point values. Most languages by default round
to some reasonable number of digits.
Java converts precisely enough that if you took the toString result and parsed
it as a double you would recover the original value. This makes the rounding
error distressingly visible. To fix it, use DecimalFormat to limit the number of
digits displayed to what you actually want/need.
Example :
double one = 23.3;
double two = 22.2;
double three = one - two;
System.out.println(three); // Output : 1.1000000000000014
System.out.println( new DecimalFormat(".##").format(three) ); // Output : 1.1