I've tried mutliple solutions to this problem but I can't seem to get it.
I have time in decimal format, which is in hours. I want to make it much cleaner by changing it into a DD:HH:MM:SS format.
10.89 hours == 10 hours, 53 minutes, 40 seconds
EDIT: 10.894945454545455 == 10 hours, 53 minutes, 40 seconds
int hours = (int) ((finalBuildTime) % 1);
int minutes = (int) ((finalBuildTime * (60*60)) % 60);
int seconds = (int) ((finalBuildTime * 3600) % 60);
return String.format("%s(h) %s(m) %s(s)", hours, minutes, seconds);
Which returned: 0(h) 41(m) 41(s)
Any suggestions?
Your calculation of minutes should just multiply by 60, not (60*60)
double finalBuildTime = 10.89;
int hours = (int) finalBuildTime;
int minutes = (int) (finalBuildTime * 60) % 60;
int seconds = (int) (finalBuildTime * (60*60)) % 60;
System.out.println(String.format("%s(h) %s(m) %s(s)", hours, minutes, seconds));
This code gives you the correct output
10(h) 53(m) 24(s)
I believe your expected output of 40 seconds is incorrect. It should be 24 seconds.
(53*60 + 24)/(60*60) = 0.89
Here is a complete implementation:
package test.std.java;
public class Test {
public static void main(String[] args) {
System.out.println(GetReadableTime(10.89));
}
//Prints outs HH:MM:SS
public static String GetReadableTime(double finalBuildTime){
int hours = (int) Math.floor(finalBuildTime);
int remainderInSeconds = (int)(3600.0* (finalBuildTime - Math.floor(finalBuildTime)) );
int seconds = remainderInSeconds % 60;
int minutes = remainderInSeconds / 60;
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
}
First part of rgettman is true :
float finalBuildTime = 10.89;
int hours = (int) finalBuildTime; // 10 ok
But (int) ((10.89 * (60 *60)) / 60) = 683 which is not what you want : it is the direct conversion of finalBuildTime
in minutes
int minutes = (int) ((finalBuildTime - hours) * 60); // 53 ok
int seconds = (int) ((finalBuildTime - hours) * 3600 - minutes * 60 + 0.5); // 24 ok
I've added 0.5 for the seconds computation to round to the nearest second rather than truncate. For your example it is no use because your time is an integer number of seconds.
And the number of seconds is 24 seconds = 0.4 minutes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With