Java:使用 currentTimeMillis() 获取时间作为 long,如何以 X 小数位精度输出它?
我有一个代表 System.currentTimeMillis()
的 long 值。然后,我稍后在代码中对时间进行了另一个测量,并将其放入 long var 中。我将两者相减,但现在想查看小数点后 3 位的时间。
目前,我在打印 long var 时使用 %d
来格式化输出并仅获取非十进制值。
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.
Currently I use %d
to format my output when printing the long var and get only non-decimal values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
long
是一个整数。它没有小数位。您的意思是您想查看小数点后三位的秒数吗?您可以对 nanoTime 执行相同的操作,但它仍然是一个整数。如果你想看到小数位,你需要除以 1e3(微秒)或 1e6(毫秒)或 1e9(秒)
long
is a whole number. It doesn't have decimal places. Do you mean you want to see seconds to three decimal places?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)
您需要将该数字除以
1000.0
,然后使用"%.3f"
显示它。所以像你需要除以双精度,因为你想要一个双精度。如果您确实除以
int
,那么它将四舍五入到最接近的 int。您不能使用%d
,因为它仅用于显示整数。您必须使用%f
来表示浮点数和双精度数。You need to divide the number by
1000.0
and then display it using"%.3f"
. So something likeYou need to divide by a
double
because you want a double. If you did divide by anint
then it would round to the nearest int. You can't use%d
because it is only used for displaying integers. You have to use%f
for floats and doubles.