is there a difference between the following code snippets?
double doubleMillis = -getSecon开发者_StackOverflowdsSinceNow()*100; // returns double
int timestamp = (int) doubleMillis;
and
int timestamp = (int) -getSecondsSinceNow()*1000;
I see differences in the values I get in timestamp. The first one seems to give me meaningful results.
When i just do:
int timestamp = -getSecondsSinceNow()*1000;
I get results similar to the first approach.
here you cast the return value of getSecondsSinceNow() (double
) to int
and multiplies it by 1000:
int timestamp = (int) -getSecondsSinceNow()*1000;
Which is like:
int timestamp = ((int) -getSecondsSinceNow())*(1000);
While in the cases below you cast the full result:
One explicitly:
double doubleMillis = -getSecondsSinceNow()*1000;
int timestamp = (int) doubleMillis;
And once implicitly:
int timestamp = -getSecondsSinceNow()*1000;
so yes, there is a difference.
Neither approach is reliable as you are casting a double which is 64 bit into a 32 bit integer. You will be losing information.
精彩评论