1000 * 60 * 60 * 24 * 30 results in a negative number
13,141
Solution 1
You are multiplying ints
together, and overflow occurs because the maximum integer is 2^31 - 1
. Only after the multiplications does it get converted to a long
. Cast the first number as a long
.
long days_30 = (long) 1000 * 60 * 60 * 24 * 30;
or use a long
literal:
long days_30 = 1000L * 60 * 60 * 24 * 30;
That will force long
math operations from the start.
Solution 2
long days_30 = 1L * 1000 * 60 * 60 * 24 * 30;
Solution 3
Just change your multiplication to long days_30 = 1000L * 60 * 60 * 24 * 30;
Author by
NoobDev954
Updated on July 27, 2022Comments
-
NoobDev954 over 1 year
I'm attempting to calculate 30 days by multiplying milliseconds however the result continually ends up being a negative number for the value of days_30 and I'm not sure why.
Any suggestions are greatly appreciated!
CODE SNIPPET:
// check to ensure proper time has elapsed SharedPreferences pref = getApplicationContext() .getSharedPreferences("DataCountService", 0); long days_30 = 1000 * 60 * 60 * 24 * 30; long oldTime = pref.getLong("smstimestamp", 0); long newTime = System.currentTimeMillis(); if(newTime - oldTime >= days_30){
days_30 value results in: -1702967296
P.S.
double days_30 = 1000 * 60 * 60 * 24 * 30; double oldTime = pref.getLong("smstimestamp", 0); double newTime = System.currentTimeMillis(); if(newTime - oldTime >= days_30){
Results in a smaller - but still negative number. -1.702967296E9
-
Rohit Jain almost 11 yearsCheck out this post
-
-
Steve Kuo almost 11 yearsA
long
is good enough in this case -
Steve Kuo almost 11 yearsIf "Computers have limitations when it comes to numbers", then how would BigInteger help?
-
rgettman almost 11 yearsIf a
double
goes beyond its range, thenPOSITIVE_INFINITY
(orNEGATIVE_INFINITY
) results, not an overflow. -
But I'm Not A Wrapper Class almost 11 yearsI'm sorry for the unclear explanation. Java limits primitive data types. For example, longs and doubles are 64 bits (excluding over head). However, if you use a Java object (or a class that extends from Object), the size can as large as the computer's memory is (or whatever the remaining space is before it crashes lol).