How to convert nanoseconds to seconds using the TimeUnit enum?

前端 未结 8 2089
小鲜肉
小鲜肉 2020-12-07 09:37

How to convert a value from nanoseconds to seconds?

Here\'s the code segment:

import java.io.*;
import java.util.concurrent.*; 
..

class Stamper          


        
8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 10:19

    Well, you could just divide by 1,000,000,000:

    long elapsedTime = end - start;
    double seconds = (double)elapsedTime / 1_000_000_000.0;
    

    If you use TimeUnit to convert, you'll get your result as a long, so you'll lose decimal precision but maintain whole number precision.

提交回复
热议问题