java 以 3 位小数显示秒。- 爪哇
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10593834/
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
Displaying seconds in 3 decimal places. - java
提问by WoLv3rine
I am using milliseconds in my java program and converting it to seconds. After my method does this, it returns seconds in a long format.
我在我的 java 程序中使用毫秒并将其转换为秒。在我的方法执行此操作后,它以长格式返回秒。
System.out.println("[" + threadID + "]" + " " + "SeqSum res=" + grandTotal + " secs=" + stopTime);
I have used the variable stopTime to display the seconds.
我使用变量 stopTime 来显示秒数。
My output is currently secs=0 It needs to be secs=0.000
我的输出目前是 secs=0 它需要是 secs=0.000
I need it to be displayed to 3 decimal places using system.out.println() or system.out.format()
我需要使用 system.out.println() 或 system.out.format() 将其显示为 3 个小数位
How can I reword my print statement so that I get the output secs=0.000?
如何改写我的打印语句,以便获得输出 secs=0.000?
Please help
请帮忙
回答by TofuBeer
Milliseconds are a long, and don't have decimal places. You will need to divide them by 1000.0f to get them into fractional seconds. Then you will need to use the format method to limit them to 3 decimal places.
毫秒很长,没有小数位。您需要将它们除以 1000.0f 才能得到小数秒。然后您将需要使用 format 方法将它们限制为 3 个小数位。
Something like:
就像是:
final long ms;
final float sec;
ms = System.currentTimeMillis();
sec = ms / 1000.0f;
System.out.format("%.3f", sec);