Kurt Wagner
Kurt Wagner

Reputation: 3325

How to convert seconds in Double to two int's for seconds and milliseconds?

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

Answers (2)

Bohemian
Bohemian

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

Simone Gianni
Simone Gianni

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 :

  1. You simply convert the double to (int) to get the integer part, that makes the seconds
  2. You subtract the seconds from the double, to obtain 0.5, an then multiply per 1000 cause they are milliseconds, and then again convert it to (int)

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

Related Questions