0

I'm trying to convert milliseconds to seconds and minutes in Java 1.4.2. I'm having trouble because my conversions are being rounded up. For example....

public String toString() {

    long startTime = System.currentTimeMillis();
    long endTime = System.currentTimeMillis();
    long elapsedTimeMillis = (endTime - startTime);

    double seconds = (double) (elapsedTimeMillis / 1000) % 60 ;
    double minutes = (double) ((elapsedTimeMillis / (1000*60)) % 60);

    return 
        " elapsedTime: " 
        + " milliseconds:" + elapsedTimeMillis 
        + " seconds:" + seconds 
        + " minutes:" + minutes;

} 

This returns results like...

elapsedTime: milliseconds:1392 seconds:1.0 minutes:0.0

and

elapsedTime: milliseconds:742 seconds:0.0 minutes:0.0123667

Instead I would like...

elapsedTime: milliseconds:1392 seconds:1.392 minutes:0.0232

and

elapsedTime: milliseconds:742 seconds:0.742 minutes:0.01236667

Seems like a simple question but I'm not sure what I'm doing wrong. Can someone help me with this.

thanks

Richie
  • 4,989
  • 24
  • 90
  • 177

1 Answers1

2

Use floating point arithmetics on division:

(elapsedTimeMillis/1000.0)

and

(elapsedTimeMillis/(1000.0*60))

correspondingly.

In other words:

double seconds =  elapsedTimeMillis / 1000.0;
double minutes = (elapsedTimeMillis / (1000.0 * 60)) % 60;
user3159253
  • 16,836
  • 3
  • 30
  • 56
  • 2
    The seconds calculation is just plain wrong, and using 1000.0 doesn't solve the underlying problem, which is that floating-point shouldn't be used at all. – user207421 Sep 12 '14 at 02:54
  • why is the seconds calcuation plain wrong? Can you please expand on this comment – Richie Sep 15 '14 at 00:18