开发者

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

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 IOEx开发者_运维技巧ception{

  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 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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜