Brian
Brian

Reputation: 414

Java casting negative Integer to Double gives wrong result

I'm trying to cast an Integer to Double but Java is giving me wrong results, i believe due to overflow.

Integer ii = -123456789;
Double dd = ii.DoubleValue();
System.out.println(dd);

I am expecting to receive -123456789.0, but instead i am getting -1.23456789E8.

Is there a way to get rid of the decimals to gain a little range in the integer part? Or another data type with bigger range?

PS. Im converting code from another language that allows this with the same number of variable bytes.

Upvotes: 0

Views: 1155

Answers (1)

Robert
Robert

Reputation: 1192

Instead of double try with BigDecimal

Integer ii = -123456789;
BigDecimal dd = new BigDecimal(ii);
System.out.println(dd);

Upvotes: 2

Related Questions