This code
Double dbl = 254.9999999999999;
Integer integ = dbl.intValue();
System.out.println(integ);
shows 254, but one "9" more
Double dbl = 254.99999999999999;
Integer integ = dbl.intValue();
System.out.println(integ);
and it is already 255.. Why?
#1) Typecasting In this way of conversion, double is typecast to int by assigning double value to an int variable. Here, Java primitive type double is bigger in size than data type int. Thus, this typecasting is called 'down-casting' as we are converting bigger data type values to the comparatively smaller data type.
To know the exact value of your double, you can use a BigDecimal:
System.out.println(new BigDecimal(254.9999999999999));
System.out.println(new BigDecimal(254.99999999999999));
prints:
254.9999999999998863131622783839702606201171875
255
So this is simply due to (limitations of) double precision...
System.out.println(254.9999999999999 == 255.0);
System.out.println(254.99999999999999 == 255.0);
prints
false
true
That should give you a hint. The double
type can represent up to 16 significant digits, and your literal has 17. Therefore the double
value nearest to the second decimal literal is 255.0
.
For the second line of code, Eclipse actually issues a warning:
Comparing identical expressions
because it is already the compiler which is aware of the fact that these are just two literals for the exact same double
value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With