7

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
AzzaClazza
  • 111
  • 3
  • 9
    Your variable is `long`, that's true. But think about it: are the numbers you multiply `long` too? – biziclop Dec 03 '15 at 15:29
  • 2
    You can avoid such explicit multiplications for time units by using the `TimeUnit` class: `long millisPerYear = TimeUnit.DAYS.toMillis(365);` – Andy Turner Dec 03 '15 at 15:37
  • @AndyTurner And of course in real life millisecond accuracy doesn't make sense on this scale, as there is a different number of milliseconds in every year. Oh, and there are at least 3 different, but equally valid definitions for "year". We usually don't have to worry about it, as the difference between them is a matter of minutes, but if you want millisecond precision, suddenly they become important. – biziclop Dec 03 '15 at 15:40
  • 1
    @biziclop I did consider naming the variable `millisPer365_24_hour_days_with_no_leap_seconds`... – Andy Turner Dec 03 '15 at 15:41

1 Answers1

16

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

user3707125
  • 3,394
  • 14
  • 23