Java:使用 currentTimeMillis() 获取时间很长,如何以 X 小数位精度输出它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7547255/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:26:00  来源:igfitidea点击:

Java: Getting time with currentTimeMillis() as a long, how do I output it with X decimal place accuracy?

javatimelong-integer

提问by KRB

I have a long that represents System.currentTimeMillis(). I then took another measurement of the time into a long var later in my code. I subtracted the two but now want to see that time to 3 decimal places.

我有一个代表System.currentTimeMillis(). 然后,我稍后在我的代码中将另一个时间测量值转换为 long var。我减去了两个但现在想看到那个时间到小数点后三位。

Currently I use %dto format my output when printing the long var and get only non-decimal values.

目前,我%d在打印 long var 时使用格式化输出并仅获取非十进制值。

回答by Peter Lawrey

longis a whole number. It doesn't have decimal places. Do you mean you want to see seconds to three decimal places?

long是一个整数。它没有小数位。你的意思是你想看到秒到小数点后三位?

long start = System.currentTimeMillis();

long time = System.currentTimeMillis() - start;
System.out.printf("Took %.3f%n", time/1e3);

You can do the same with nanoTime, but it is still a whole number. If you want to see decimal places you need to divide by 1e3 (micro-seconds) or 1e6 (milli-seconds) or 1e9 (seconds)

你可以用 nanoTime 做同样的事情,但它仍然是一个整数。如果要查看小数位,则需要除以 1e3(微秒)或 1e6(毫秒)或 1e9(秒)

回答by Amir Raminfar

You need to divide the number by 1000.0and then display it using "%.3f". So something like

您需要将数字除以1000.0,然后使用"%.3f". 所以像

String.format("%.3f", number / 1000.0)

You need to divide by a doublebecause you want a double. If you did divide by an intthen it would round to the nearest int. You can't use %dbecause it is only used for displaying integers. You have to use %ffor floats and doubles.

你需要除以 adouble因为你想要一个双倍。如果你确实除以 anint那么它会四舍五入到最近的 int。您不能使用,%d因为它仅用于显示整数。你必须使用%f浮动和双打。