简体   繁体   中英

How do I format a double into a time with a print statement in Java?

I'm trying to format a double into a time in Java.

Here is my current code:

int food_intake = 1000;
int calories_burned_per_hour = 173
double hours = food_intake / calories_burned_per_hour;
System.out.println("It will take you " + hours + " hours to burn that food off");

Here is the current output:

It will take you 5.78034682 hours to burn that food off

Here is the desired output:

It will take you 5 hours and 46 minutes to burn that food off

Any help is much appreciated - thank you in advance!

You have to calculate the min part separately as below -

int food_intake = 1000;
int calories_burned_per_hour = 173;
double hours = food_intake / (calories_burned_per_hour * 1.0);

int hrPart = (int) hours;
int minPart = (int) ((hours - hrPart) * 60);

System.out.println("It will take you " + hrPart + " hours and " + minPart + " min to burn that food off");

Duration

The java.time.Duration class represents a span of time unattached to the timeline on the scale of hours, minutes, seconds, and nanos.

Duration works only with integer numbers, not fractional. So multiply your double to the granularity you desire: minutes, seconds, or nanos.

double hours = 5.78034682d ;
double minutes = ( hours * 60d ) ; 
Duration d = Duration.ofMinutes( minutes ) ;

String output = d.toString() ;  // Standard ISO 8601 format. 
String h = d.toHoursPart() ;
String m = d.toMinutesPart() ;

Now ready to assemble your final string.

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