What is a scientific notation and why is double printed in scientific notation in Java?

徘徊边缘 提交于 2020-01-07 03:58:09

问题


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 to 10^-3 but less than 10^7, then it is represented as the integer part of m, in decimal form with no leading zeroes, followed by '.' ('\u002E'), followed by one or more decimal digits representing the fractional part of m.
  • If m is less than 10^-3 or greater than or equal to 10^7, then it is represented in so-called "computerized scientific notation." Let n be the unique integer such that 10^n ≤ m < 10^n+1; then let a be the mathematically exact quotient of m and 10^n so that 1 ≤ a < 10. The magnitude is then represented as the integer part of a, as a single decimal digit, followed by '.' ('\u002E'), followed by decimal digits representing the fractional part of a, followed by the letter 'E' ('\u0045'), followed by a representation of n as a decimal integer, as produced by the method Integer.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!