问题
I use this code:
long elapsedTime = now - lastTime;
delta = ((double) elapsedTime) / 1000000000;
System.out.println(elapsedTime);
System.out.println(delta);
This is my output:
173290
1.7329E-4
This output gives me scientific notation, but I don't know what it is. Can you explain me? And why is double printed in scientific notation?
回答1:
The output you're seeing is scientific notation.
In Java, double is printed as scientific notation if the magnitude is less than 10^-3
or greater than 10^7
.
Double#toString() javadocs
For a magnitude m
:
- If
m
is greater than or equal to10^-3
but less than10^7
, then it is represented as the integer part ofm
, in decimal form with no leading zeroes, followed by'.' ('\u002E')
, followed by one or more decimal digits representing the fractional part ofm
. - If
m
is less than10^-3
or greater than or equal to10^7
, then it is represented in so-called "computerized scientific notation." Letn
be the unique integer such that10^n ≤ m < 10^n+1;
then leta
be the mathematically exact quotient ofm
and10^n
so that1 ≤ a < 10
. The magnitude is then represented as the integer part ofa
, as a single decimal digit, followed by'.' ('\u002E')
, followed by decimal digits representing the fractional part ofa
, followed by the letter'E' ('\u0045')
, followed by a representation ofn
as a decimal integer, as produced by the methodInteger.toString(int)
.
Since your output of 1.7329E-4
has a magnitude of 10^-4
, it falls under the second category, per listed above.
回答2:
You should consider using the java.util.concurrent.TimeUnit
. It's easier to read and less error-sensitive.
TimeUnit.NANOSECONDS.toSeconds(timeInSeconds)
来源:https://stackoverflow.com/questions/44026121/what-is-a-scientific-notation-and-why-is-double-printed-in-scientific-notation-i