Java 如何正确显示纳米时间到秒的转换

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

how correctly display nanotime to second conversion

javananotime

提问by chris edwards

I have a BFS algorithm to solve the 8-Puzzle, and one of the project requirements is to output the amount of time it takes to find the shallowest solution.

我有一个BFS算法来解决8-Puzzle,项目需求之一是输出找到最浅解所花费的时间。

I am using System.nanoTime()to keep track of the applications run time because it solves the majority of the given puzzles in well under a second.

System.nanoTime()用来跟踪应用程序的运行时间,因为它在一秒钟内解决了大多数给定的难题。

The problem i am having is whem i convert my nanoTimeto seconds, it displays in a weird format.

我遇到的问题是我将我转换nanoTime为秒,它以奇怪的格式显示。

the following code is used:

使用以下代码:

final long startTime = System.nanoTime();

//algorithm code removed for simplicity this all functions correctly


final long duration = System.nanoTime() - startTime;
final double seconds = ((double)duration / 1000000000);
System.out.println("Nano time total: " + duration);
System.out.println("solution Time : " + seconds + " Seconds");

This produces the output:

这会产生输出:

 Nano time total: 916110
 solution time : 9.1611E-4 Seconds 

I have also tried using floats to represent the values.

我也尝试过使用浮点数来表示值。

is anybody able to provide a better way to convert/display, maybe use a format output statement?

有没有人能够提供更好的转换/显示方式,也许使用格式输出语句?

Thanks for taking the time to read my question.

感谢您花时间阅读我的问题。

采纳答案by akasha

I think you need: DecimalFormat

我认为你需要:DecimalFormat

System.out.println("solution Time : " + new DecimalFormat("#.##########").format(seconds) + " Seconds");

回答by Amadan

System.out.format("solution Time : %f Seconds", seconds);

for the classic, non-exponential floating point number.

对于经典的非指数浮点数。