Java - Converting hours(in double) to minutes(integer) and vice versa

uno picture uno · Aug 12, 2011 · Viewed 17.5k times · Source

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);
  }
} 

Answer

Bohemian picture Bohemian · Aug 12, 2011

That's because casting to int truncates the fractional part - it doesn't round it:

8.16 * 60 = 489.6

When cast to int, it becomes 489.

Consider using Math.round() for your calculations:

int min = (int) Math.round(hours * 60);

Note: double has limited accuracy and suffers from "small remainder error" issues, but using Math.round() will solve that problem nicely without having the hassle of dealing with BigDecimal (we aren't calculating inter-planetary rocket trajectories here).

FYI, to convert minutes to hours, use this:

double hours = min / 60d; // Note the "d"

You need the "d" after 60 to make 60 a double, otherwise it's an int and your result would therefore be an int too, making hours a whole number double. By making it a double, you make Java up-cast min to a double for the calculation, which is what you want.