Antoine
Antoine

Reputation: 936

Java DecimalFormat with only negative exponents

I am unable to define DecimalFormat instance (in Java1.8) with the following properties:

(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]));
}

Upvotes: 2

Views: 456

Answers (2)

Diasiare
Diasiare

Reputation: 755

I don't think you can achieve your goal using the normal DecimalFormatter class. If everything uses the same instance of DecimalFormatter then you might be able to subclass DecimalFormatter and then apply something like tristan's answer inside the overwritten format method.

If you do this make sure that the parse method isn't used anywhere, or if it is make sure to override that too.

Upvotes: 0

tristan
tristan

Reputation: 128

You can try an if statement to check if the number is below 1.

if (xs < 1) {
    System.out.println("Representation of " + xsStr[i] + ": " + df.format(xs[i]));
}
else {
    System.out.println("Representation of " + xsStr[i] + ": " + xs[i];
}

Another option would be to use a ternary operator.

System.out.println("Representation of " + xsStr[i] + ": " + xs[i] < 1 ? df.format(xs[i]) : xs[i]);

This answer does a good job at explaining how it works. https://stackoverflow.com/a/25164343/

Upvotes: 2

Related Questions