Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

flutter - NumberFormat strange Rounding behaviour with German Locale

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I used the package number_display.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...