首页 > 解决方案 > 德语区域设置的 NumberFormat 奇怪的舍入行为

问题描述

我有一个颤动的 TextField,我想在其中输入德语数字(Decimalseparator: , - Thousandseparator: .)。为此,我使用 TextInputFormatter,在其中使用 NumberFormat。

但是 NumberFormat.format(1.9999) 会自动四舍五入为二。如何影响 Numberformat 或如何使用具有不同实现的 Textinput 实现德语区域设置?

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);
}
}

标签: flutterdartroundingtextfieldnumber-formatting

解决方案


我使用了包 number_display。

final display =
createDisplay(length: 100, separator: '.', decimalPoint: ',');
newText = display(number);

推荐阅读