Java - 将小时(双倍)转换为分钟(整数),反之亦然
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7037706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Converting hours(in double) to minutes(integer) and vice versa
提问by uno
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.
我需要正确的公式来将小时转换为分钟,反之亦然。我写了一个代码,但它似乎没有按预期工作。例如:如果我有 hours=8.16,那么分钟应该是 490,但我得到的结果是 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);
}
}
回答by Bohemian
That's because casting to int
truncatesthe fractional part - it doesn't round it:
那是因为强制转换会int
截断小数部分 - 它不会四舍五入:
8.16 * 60 = 489.6
When cast to int
, it becomes 489.
当转换为 时int
,它变为 489。
Consider using Math.round()
for your calculations:
考虑使用Math.round()
您的计算:
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).
注意:double
精度有限并且存在“小余数误差”问题,但使用Math.round()
将很好地解决该问题而无需处理BigDecimal
(我们在这里不计算行星际火箭轨迹)。
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.
你需要在“d”之后加上60
60 a double
,否则它是 an int
,因此你的结果也会是 an int
,使hours
整数翻倍。通过将其设置为 a double
,您可以将 Java 向上转换为 min 以进行计算,这正是您想要的。
回答by Ankit
8.16 X 60 comes out to be 489.6 and if you convert this value to int, you will get 489
8.16 X 60 结果是 489.6,如果你把这个值转换成 int,你会得到 489
int a = (int)489.6;
System.out.println("Minutes:=" + a);