8

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.

Petter Bjao
  • 327
  • 1
  • 3
  • 10

5 Answers5

7

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;
Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55
  • 1
    That's a real shame because one of the principal reasons to use a convert method is because writing out all those 0's is so error prone. – demongolem Mar 14 '16 at 19:27
6

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.

AlexWien
  • 28,470
  • 6
  • 53
  • 83
4

Just divide by 1,000,000:

double millis = 665477 / 1000000.0;

With TimeUnit you will only get an integer result.

sina72
  • 4,931
  • 3
  • 35
  • 36
3

You can calculate this manualy

double mil = 665477L/1_000_000.0
schlagi123
  • 715
  • 4
  • 11
0
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.

Sebien
  • 821
  • 8
  • 11