简体   繁体   中英

convert milliseconds to seconds, minutes without rounding

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

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;

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