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.
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.
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;
shorter and less error prone:
double millis = 665477 / 1E6;
milli -> mikro -> nano
are two steps, each step has a conversion faktor of 1000 = 1E3; So makes one million, which can easier be read as 1E6, than by counting zeros.
Just divide by 1,000,000:
double millis = 665477 / 1000000.0;
With TimeUnit
you will only get an integer result.
double milliSeconds = nanoSeconds / (double) TimeUnit.MILLISECONDS.toNanos(1);
so you don't have to put the magic number 1_000_000.0 in your code, or remember what is the correct ratio to make sure there is no bug: the line is pretty self-validating.
You can import static java.util.concurrent.TimeUnit.MILLISECONDS;
for a code reading even more like prose.