-1

Right now, Java is printing 7.1781566186590595E-6. I want it to print 7.17E-6.

I searched this up, but I only found how to reduce digits without scientific notation (so it will end up like 0.00 because the number is small).

2 Answers2

3

Use format specifier "%.3g", tutorial here

float f = 7.1781566186590595E-6f;
System.out.format("%.3g", f);

Output

7.18e-06

Note, you mentioned 7.17E-6 in your question as desired output, but that's not correctly rounded - should be 7.18e-06

rkosegi
  • 14,165
  • 5
  • 50
  • 83
2

You can use String.format method to format and create your String, than you can use it like any String.

Therefore the "%.3g" format should be used like this:

double myDouble = 1/12345678d;
System.out.println(String.format("%.3g", myDouble));

Will result in: 8,10e-08.

Note: The ".3" in the format specifies the precision. In case you want more or less digits you can simply change the number to your needs like e.g. "%.5g" in case you want two extra digits. You can also exchange the small "g" with "G" it'll print a capital "E" instead of the small "e".

In case you prefer the "." instead of the "," as a separator you can additionally explicitly specify the local to be used in the formatter like the following:

double myDouble = 1/12345678d;
System.out.println(String.format(Locale.ENGLISH, "%.3g", myDouble));

Will result in: 8.10e-08.

More information can be found in the JavaDoc of String.format here.


EDIT:

Interesting in your case:

When you use the format string as above (with the 'g') "%.3g" it'll round your value in the mathematical correct way. When you change the format string and use it with an 'e' "%.3e" it'll not round it and treat your number as a literal:

Code:

double myDouble = 7.1781566186590595E-6d;
System.out.println(String.format(Locale.ENGLISH, "%.3e", myDouble));
System.out.println(String.format(Locale.ENGLISH, "%.3g", myDouble));

Result:

7.178e-06 // using "%.3e" => literal, therefore not rounded
7.18e-06  // using "%.3g" => rounded
Sebsen36
  • 447
  • 3
  • 10