3

While playing around with double string formatting, I noticed that, at least on my locale, the strings produced by a default DecimalFormat object are different than the ones generated by Double.toString() when it comes to special cases like Infinity and NaN. E.g. from this snippet:

for (double i : new double[]{ 1/0.0, -1/0.0, 0/0.0 }) {
    System.out.println(Double.toString(i));
    System.out.println(new DecimalFormat().format(i));
}

I get this output:

Infinity
∞
-Infinity
-∞
NaN
�

This not only causes issues with existing code that is watching out for NaN and Infinity, but the last symbol is unreadable with the fonts on my development system. As far as I can tell by checking its numeric value, that last symbol is the U+FFFD Unicode replacement character, which probably means that it has not actually been set to something meaningful.

Since for some of my applications I prefer the 7-bit ASCII representations ("Be liberal in what you accept, be conservative in what you produce"), is there some way to force the strings produced by DecimalFormat to match those produced by Double.toString()?

One way might be to provide a DecimalFormatSymbols of my own, but it seems that I'd have to set all related fields myself, which sounds somewhat fragile. Is there a way to avoid that?

thkala
  • 84,049
  • 23
  • 157
  • 201

1 Answers1

2

Unfortunately the only way to change it using DecimalFormatSymbols class.

http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

you can get the DecimalFormatSymbols object from your DecimalFormat and modify it. see the below code snippet. So you don't need to set all fields.

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
dfs.setNaN("NaN");
df.setDecimalFormatSymbols(dfs);
sasankad
  • 3,543
  • 3
  • 24
  • 31
  • I'll accept this answer, since this seems to be the actual answer, disappointing as it is... – thkala Dec 25 '11 at 17:29
  • `getDecimalFormatSymbols` returns a copy of the internal object, so modifying it will not modify the symbols of the existing DecimalFormat object. You will need to call `setDecimalFormatSymbols` or pass a DecimalFormatSymbols object in the DecimalFormat constructor. – Mikkel Aug 26 '14 at 00:32
  • As @Mikkel noted, you are missing an additional instruction: `df.setDecimalFormatSymbols(dfs);` – jcfrei Feb 17 '16 at 14:49
  • 1
    @jcfrei, modified the answer. Thanks – sasankad Feb 18 '16 at 06:03