Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Double.intValue() work?

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?

like image 675
Artem Ruchkov Avatar asked Feb 06 '14 12:02

Artem Ruchkov


People also ask

How can a double value be assigned to an integer variable?

#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.


2 Answers

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...

like image 125
assylias Avatar answered Oct 16 '22 18:10

assylias


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.

like image 13
Marko Topolnik Avatar answered Oct 16 '22 19:10

Marko Topolnik