I am unable to define DecimalFormat
instance (in Java1.8) with the following properties:
- Scientific notation (exponent) is used only if the exponent is negative.
- At most 4 significant places are shown, i.e., no 0s at the end.
(I can live without the second property being satisfied if necessary.)
The purpose is to convert doubles to strings, i.e., to use the format
method. Here is the desired behaviour on some examples:
Representation of 9: 9
Representation of 9.0: 9
Representation of 9876.6: 9877
Representation of 0.0098766: 9.877E-3
Representation of 0.0000000098766: 9.877E-9
If I define DecimalFormat df = new DecimalFormat("#.###E0");
, this gives
Representation of 9: 9E0
Representation of 9.0: 9E0
Representation of 9876.6: 9.877E3
Representation of 0.0098766: 9.877E-3
Representation of 0.0000000098766: 9.877E-9
which is wrong in the first three cases. Things like DecimalFormat("#.###E#")
or DecimalFormat("#.###E")
are not allowed (IllegalArgumentException
is thrown).
The code that produced the output is given below.
DecimalFormat df = new DecimalFormat("#.###E0");
double[] xs = new double[] {9, 9.0, 9876.6, 0.0098766, 0.0000000098766};
String[] xsStr = new String[] {"9", "9.0", "9876.6", "0.0098766", "0.0000000098766"};
for(int i = 0; i < xs.length; i++) {
System.out.println("Representation of " + xsStr[i] + ": " + df.format(xs[i]));
}