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

人盡茶涼 提交于 2019-12-22 09:00:04

问题


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

回答1:


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.




回答2:


8.16 X 60 comes out to be 489.6 and if you convert this value to int, you will get 489

int a = (int)489.6;
      System.out.println("Minutes:=" + a);


来源:https://stackoverflow.com/questions/7037706/java-converting-hoursin-double-to-minutesinteger-and-vice-versa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!