简体   繁体   中英

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

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()

You are doing far more work than you need to do.

Just pass a Locale to the NumberFormat.getInstance method. It will take care of the symbols based on that Locale. The default behavior is already to hide the decimal point if the value being formatted with no decimal digits.

NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH);
numberFormat.setGroupingUsed(false);
String valueStr = numberFormat.format(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM