开发者

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

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.


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

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)


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

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

You need to divide by a double because you want a double. If you did divide by an int 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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜