Joza100
Joza100

Reputation: 356

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

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?

Upvotes: 0

Views: 353

Answers (2)

victorantunes
victorantunes

Reputation: 1169

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.

Upvotes: 2

Mathias Pahlen
Mathias Pahlen

Reputation: 130

You should consider using the java.util.concurrent.TimeUnit. It's easier to read and less error-sensitive.

TimeUnit.NANOSECONDS.toSeconds(timeInSeconds)

Upvotes: 1

Related Questions