Reputation: 3325
I have an arbitrary Double variable that represents seconds and I'm looking to convert into two ints so I can add to the Calendar object, but can't figure out how to basically split a double into it's decimal and integer values. I'd be open to other implementations if any better ones exist to add a Double seconds variable to a calendar.
Double someDouble = 2.5;
int seconds = 0, milli = 0;
//Get seconds to = 2, milli to = 500 from someDouble (pad with zeroes to get three places)
Calendar someCalendar = Calendar.getInstance();
someCalendar.add(Calendar.SECOND, seconds);
someCalendar.add(Calendar.MILLISECOND, milli);
Upvotes: 3
Views: 7199
Reputation: 425448
Use integer arithmetic:
int seconds = someDouble.intValue();
int millis = (int)(someDouble * 1000) % 1000;
The Double class offers the intValue()
method, so that's seconds
sorted out.
millis
is just the remainder after dividing the number of milliseconds by 1000, so the modulus operator %
is all you need (the number of seconds is irrelevant to this calculation).
Upvotes: 3
Reputation: 11672
You don't need to work with a calendar for this, there is a faster way :
int seconds = (int)someDouble.doubleValue();
int milli = (int)((someDouble.doubleValue() - seconds) * 1000);
What is going on here is :
If instead of Double you had double, also the doubleValue() call could be omitted :
double dtime = 2.5d; // or someDouble.doubleValue() if you need to convert
int seconds = (int)dtime;
int milli = (int)((dtime - seconds) * 1000);
Upvotes: 3