开发者

Casting a negated double to int

开发者 https://www.devze.com 2023-03-09 10:27 出处:网络
is there a difference between the following code snippets? double doubleMillis = -getSecon开发者_StackOverflowdsSinceNow()*100; // returns double

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消