I need the correct formula that will convert hours to minutes and vice versa.
I have written a code, but it doesn’t seem to work as expected.
For eg:
If I have hours=8.16, then minutes should be 490, but I’m getting the result as 489.
import java.io.*;
class DoubleToInt {
public static void main(String[] args) throws IOException{
BufferedReader buff =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the double hours:");
String d = buff.readLine();
double hours = Double.parseDouble(d);
int min = (int) ((double)hours * 60);
System.out.println("Minutes:=" + min);
}
}
That’s because casting to
inttruncates the fractional part – it doesn’t round it:When cast to
int, it becomes 489.Consider using
Math.round()for your calculations:Note:
doublehas limited accuracy and suffers from “small remainder error” issues, but usingMath.round()will solve that problem nicely without having the hassle of dealing withBigDecimal(we aren’t calculating inter-planetary rocket trajectories here).FYI, to convert minutes to hours, use this:
You need the “d” after
60to make 60 adouble, otherwise it’s anintand your result would therefore be aninttoo, makinghoursa whole number double. By making it adouble, you make Java up-cast min to a double for the calculation, which is what you want.