Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get decimal result when converting nanosecond to millisecond?

Tags:

java

timeunit

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.

like image 627
Petter Bjao Avatar asked Jul 07 '14 12:07

Petter Bjao


People also ask

How many decimals is a nanosecond?

A nanosecond (ns) is a unit of time in the International System of Units (SI) equal to one billionth of a second, that is, 1⁄1 000 000 000 of a second, or 10−9 seconds.

Which conversion factor would be needed to convert nanoseconds to milliseconds?

There are 0.000001 milliseconds in a nanosecond.

How do you convert nanoseconds to milliseconds on Excel?

How to Convert Nanoseconds to Milliseconds. To convert a nanosecond measurement to a millisecond measurement, divide the time by the conversion ratio. The time in milliseconds is equal to the nanoseconds divided by 1,000,000.

Is nanoseconds and milliseconds the same?

Nanosecond is one billionth of a second. Microsecond is one millionth of a second. Millisecond is one thousandth of a second.


2 Answers

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.

like image 33
AlexWien Avatar answered Nov 02 '22 21:11

AlexWien


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;
like image 123
Ninad Pingale Avatar answered Nov 02 '22 22:11

Ninad Pingale