Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why these two has different values?

Tags:

java

Double milisecondsInYear = 365*24*3600*1000;

It's 1.7e9

But if I used

Double milisecondsInYear = 365*24*3600*1000.;

I got correct answer 3.15E10

like image 205
Jumpworker Avatar asked Nov 21 '25 06:11

Jumpworker


1 Answers

Because 365, 24, 3600 and 1000 are all int literals, the calculation is done using ints. The multiplication overflows because the true value exceeds Integer.MAX_VALUE. By putting a dot at the end you turn that last literal into a double literal. This is not a very robust way to correct it because the multiplication of the first 3 numbers is still carried out using ints. The best way to deal with this is to make the first number a long or double literal.

365L*24*3600*1000

or

365.0*24*3600*1000
like image 85
Paul Boddington Avatar answered Nov 22 '25 20:11

Paul Boddington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!