Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Java Math Result [duplicate]

Tags:

java

math

Really simple question but perhaps someone can explain. I have 2 lines of code:

long millisPerYear = 365*24*60*60*1000;
System.out.println("millis per year = " + millisPerYear);

I expect the output of 31 536 000 000 but I get 1 471 228 928.

If I remove the 1000 from the formula the answer is correct but the 1000 pushes it over the edge.

The variables format is Long so it should be 264 in size, plenty big enough. I'm stumped as to why the values isn't being stored accurately.

like image 344
AzzaClazza Avatar asked Dec 03 '15 15:12

AzzaClazza


1 Answers

You are making computation on the right-hand side using only ints. Replace 365 with 365L to perform computation in long.

like image 114
user3707125 Avatar answered Oct 21 '22 22:10

user3707125