文本分隔符上的千位分隔符不带小数点分隔符 [英] Thousand separator without decimal separator on TextFormField flutter
问题描述
我使用 flutter_masked_text 来格式化我的控制器,以便自动在我的货币字段中添加千位分隔符。
Am using flutter_masked_text in order to format my controller to automatically add thousand separator to my currency field. Am using this to achieve that.
var controller = new MoneyMaskedTextController(decimalSeparator: '.', thousandSeparator: ',');
我不喜欢它的工作方式,因为它从 0.00开始
并自动开始从小数部分开始添加数字。如果我输入 1000
,它应该变成 1,000
而不是 1,000.00
。有没有办法格式化控制器字段以添加不带小数点分隔符的千位分隔符?
I don't like the way it works because it starts from 0.00
and automatically starts adding digits from the decimal section. If I type 1000
, it should become 1,000
not 1,000.00
. Is there a way I can format my controller field to add thousand separator without decimal separator?
推荐答案
我使用了自定义文本输入格式程序做这样的事情:
I used a custom text input formatter to do something like that :
class CustomTextInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.length == 0) {
return newValue.copyWith(text: '');
} else if (newValue.text.compareTo(oldValue.text) != 0) {
int selectionIndexFromTheRight =
newValue.text.length - newValue.selection.extentOffset;
List<String> chars = newValue.text.replaceAll(' ', '').split('');
String newString = '';
for (int i = 0; i < chars.length; i++) {
if (i % 3 == 0 && i != 0) newString += ' ';
newString += chars[i];
}
return TextEditingValue(
text: newString,
selection: TextSelection.collapsed(
offset: newString.length - selectionIndexFromTheRight,
),
);
} else {
return newValue;
}
}
}
然后在您的TextField上:
Then on your TextField:
TextField(
controller: _textController,
keyboardType: TextInputType.number,
inputFormatters: [CustomTextInputFormatter()],
)
这篇关于文本分隔符上的千位分隔符不带小数点分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!