作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在 TextField
中,我有一个初始文本 0.00
那么一旦用户开始在 Flutter 中输入,我该如何格式化输入的值?我目前正在使用 flutter_money_formatter包,但我无法获得预期的行为。
例如,如果用户键入数字:1.800.45
,我想要以下行为:
当用户点击 1 时。我们应该有 0.01
当用户点击 8 时,我们应该显示 0.18
当用户点击 0 时。我们应该显示 1.80
当用户点击 0 时。我们应该显示 1.800
当用户点击 4 时,我们应该显示 1.800,4
当用户点击 5 时。我们应该显示 1.800,45
。
我当前的代码:
class _MoneyTextFormField extends StatelessWidget {
TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return TextFormField(
controller: _controller,
style: TextStyle(color: context.primaryColor),
keyboardType: TextInputType.number,
inputFormatters: [
TextInputFormatter.withFunction((oldValue, newValue) {
// remove characters to convert the value to double (because one of those may appear in the keyboard)
String newText = newValue.text.replaceAll(MoneyTextFormField._cents, '')
.replaceAll('.', '')
.replaceAll(',', '')
.replaceAll('_', '')
.replaceAll('-', '');
String value = newText;
int cursorPosition = newText.length;
if (newText.isNotEmpty) {
value = formatCurrency(double.parse(newText), fractionDigits: 0);
cursorPosition = value.length;
}
return TextEditingValue(
text: value,
selection: TextSelection.collapsed(offset: cursorPosition)
);
}),
],
);
}
}
格式化值的函数:
/// Format the giving value and return the value as String
/// Note: the parameter should be a int or double
static String formatCurrency(num value,{int fractionDigits = 2}) {
ArgumentError.checkNotNull(value, 'value');
return FlutterMoneyFormatter(
amount: value.toDouble(),
settings: MoneyFormatterSettings(
thousandSeparator: '.',
decimalSeparator: ',',
fractionDigits: fractionDigits
),
).output.nonSymbol;
}
注意:这不是 this one 的副本因为该解决方案不适用于 Flutter。
最佳答案
我刚刚使用 Intl 包找到了解决方案。只需使用下面的 formatCurrency
方法,一切都会得到解决。
注意:该值应始终以美分为单位。这就是为什么我们将它除以 100 得到美分并将结果传递给格式化程序的原因。
static String formatCurrency(num value,{int fractionDigits = 2}) {
ArgumentError.checkNotNull(value, 'value');
// convert cents into hundreds.
value = value / 100;
return NumberFormat.currency(
customPattern: '###,###.##',
// using Netherlands because this country also
// uses the comma for thousands and dot for decimal separators.
locale: 'nl_NL'
).format(value);
}
关于flutter - 如何在 Flutter 的 TextField 上格式化输入货币(从右到左)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62391643/
我是一名优秀的程序员,十分优秀!