简体   繁体   中英

DecimalFormat: wrong digit after comma

i have a problem with DecimalFormat. In my code i have:

Double value = 1.40;
DecimalFormat df = new DecimalFormat("###,###,###.00########");
df.setGroupingUsed(true);
df.setDecimalSeparatorAlwaysShown(true);
System.out.println(df.format(value));

Now, with this code, theoritically, i should have:

1.40

but, when the value is formatted i have an output like this:

1.3999999762

Why does this happen? How can i resolve it? Thanks for the answers!

This is not a problem of DecimalFormat , it is a problem of the way binary float point numbers work . Certain numbers are not representable this way, so you get an approximation to them - like in your case.

Using BigDecimal is a possible solution.

You should avoid using DecimalFormat directly. You may try like this:

NumberFormat f = NumberFormat.getInstance(Locale.GERMANY);
if (f instanceof DecimalFormat) {
    ((DecimalFormat) f).applyPattern("###,###,###.00########");
}

IDEONE

Using BigDecimal is good alternative.

The Oracle docs says:

To obtain a NumberFormat for a specific locale, including the default locale, call one of NumberFormat's factory methods, such as getInstance(). In general, do not call the DecimalFormat constructors directly , since the NumberFormat factory methods may return subclasses other than DecimalFormat.

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