简体   繁体   中英

Casting a negated double to int

is there a difference between the following code snippets?

double doubleMillis = -getSecondsSinceNow()*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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM