javadecimalformat

DecimalFormat strange behaviour


I am having some trouble trying to figure it out what is happening to me with the DecimalFormat.

I have the following code:

DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setDecimalSeparator(decimalSeparator); 
decimalFormatSymbols.setGroupingSeparator(thousandSeparator);

DecimalFormat decimalFormat = new DecimalFormat("###0.######", decimalFormatSymbols);
decimalFormat.setDecimalSeparatorAlwaysShown(numberDecimal > 0);
decimalFormat.setMinimumFractionDigits(numberDecimal);
decimalFormat.format(Double.valueOf(value));

Where decimalSeparator is '.', thousandSeparator is ',' and value is an String an is equals to 100.000000

Running the above code the result is equals to: 100.000000

Whereas if I run the following code:

DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setDecimalSeparatorAlwaysShown(numberDecimal > 0);
decimalFormat.setMinimumFractionDigits(numberDecimal);
decimalFormat.applyPattern("###0.######");
decimalFormat.setDecimalFormatSymbols(decimalFormatSymbols);

The result is: 100

Which is the result I want to, because I need to get rid of the zeros at the end.

What it is the difference between using the constructor or the setter methods?

Am I dealing with the DecimalFormat in the right why? Or will I be in trouble if a execute this code in another machine with for example another Locale?

Note: The requirement is to have a number with '.' as decimalSeparator, but without zeros at the end, and without thousandSeparator character. For example: 3,000,000.000 -> 3000000 99.939.000 -> 99.939


Solution

  • A DecimalFormat comprises a pattern and a set of symbols. The pattern may be set directly using applyPattern(), or indirectly using the API methods. The symbols are stored in a DecimalFormatSymbols object. When using the NumberFormat factory methods, the pattern and symbols are read from localized ResourceBundles.

    If you take a look at the source code of DecimalFormat.java, you'll see that applyPattern() calls this.setMaximumFractionDigits()