I have a flutter TextField in which I want to input German numbers (Decimalseparator: , - Thousandseparator: .). For this I use a TextInputFormatter in which I work with NumberFormat.
However NumberFormat.format(1.9999) is automatically rounded to two. How can I influence the Numberformat or how can I achieve German Locale with Textinput with different implementations?
class GermanDecimalInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text == '')
return newValue.copyWith(
text: '0',
selection: newValue.selection
.copyWith(baseOffset: newValue.selection.baseOffset + 1));
String newText = newValue.text.replaceAll('.', '');
final deFormat = NumberFormat.decimalPattern(
'de',
);
try {
var number = deFormat.parse(newText);
newText = deFormat.format(number); // re-adds thousand separator
if (newValue.text.endsWith(',')) newText += ',';
} catch (e) {
return oldValue;
}
var shift = newValue.text.length - newText.length;
TextSelection newSelection = TextSelection.fromPosition(
TextPosition(offset: newValue.selection.baseOffset - shift));
return TextEditingValue(text: newText, selection: newSelection);
}
}
question from:
https://stackoverflow.com/questions/65832945/numberformat-strange-rounding-behaviour-with-german-locale 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…