In this GIF, you can see what is wrong:
The code for this JFormattedTextField and the JFormatter looks like this:
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.GERMANY);
format.setMaximumFractionDigits(2);
NumberFormatter formatter = new NumberFormatter(format);
formatter.setAllowsInvalid(false);
formatter.setOverwriteMode(true);
JFormattedTextField price = new JFormattedTextField(formatter);
price.setValue(0.00);
Every time a number hits the separator, it adds two additional zeros. How can I prevent that?

You are overwriting the decimal separator. When the contained text is
1,00 €, corresponding to1.0, and you overwrite the,with1, the resulting text first is1100 €which will be parsed to1100.0as theNumberFormatis tolerant regarding absent or misplaced grouping separators, as well as absent fractional parts. The number1100.0is then reformatted to1.100,00 €.This repeats when you continue typing.
The fact that the comma gets overwritten seems to be a bug. I found the following code in the
NumberFormatter:Contrary to the documentation comment’s enumeration, which mentions “decimal separator”, the field
NumberFormat.Field.DECIMAL_SEPARATORis not handled within the method.Since this is a package-private method, as most of the implementation, there is no way to alter this behavior from an application. We can place a work-around at the incoming
NumberFormatside, by creating a customNumberFormatwhich removes the marker for theDECIMAL_SEPARATORat the character iterator already.First, we add a helper method
Then, change the example usage to
The custom
NumberFormatdelegates to the original format in almost every regard. The only difference is that theDECIMAL_SEPARATORattribute gets removed from the character iterator, so the decimal separator will be treated like literal text of the format which can not be changed.As a result, you can type straight-forwardly in overwrite mode. However, the handling of a
JFormattedTextFieldin overwrite mode still is tricky. You need tosetMinimumIntegerDigits(…)to make writing numbers with more digits easier, but deleting decimal digits will become unintuitive then.