javatimeunit

How to get decimal result when converting nanosecond to millisecond?


Using TimeUnit, how can I convert 665477 nanosecond to 0.665477 millisecond?

long t = TimeUnit.MILLISECONDS.convert(665477L, TimeUnit.NANOSECONDS);

This always gives 0 but I need decimal points precision.


Solution

  • From Java Documentation - TimeUnit#convert

    public long convert(long sourceDuration,TimeUnit sourceUnit)
    

    Convert the given time duration in the given unit to this unit. Conversions from finer to coarser granularities truncate, so lose precision. For example converting 999 milliseconds to seconds results in 0. Conversions from coarser to finer granularities with arguments that would numerically overflow saturate to Long.MIN_VALUE if negative or Long.MAX_VALUE if positive.

    So to get your answer

    double milliseconds = 665477 / 1000000.0;