flutter - 格式化没有小数点的文本输入字段
问题描述
我试图在 FormField 中将数字字符串显示为货币格式。我正在使用inputFormatter
来实现这一点。我希望字符串以这种方式返回:1,000
但它以十进制返回,例如1,000.00
inputFormatters: [
WhitelistingTextInputFormatter.digitsOnly,
CurrencyPtBrInputFormatter()
],
CurrencyFormatter类
class CurrencyPtBrInputFormatter extends TextInputFormatter {
CurrencyPtBrInputFormatter({this.maxDigits});
final int maxDigits;
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.selection.baseOffset == 0) {
return newValue;
}
if (maxDigits != null && newValue.selection.baseOffset > maxDigits) {
return oldValue;
}
int value = int.parse(newValue.text);
final formatter = new NumberFormat.simpleCurrency(locale: "en");
String newText = "N" + formatter.format(value / 100);
return newValue.copyWith(
text: newText,
selection: new TextSelection.collapsed(offset: newText.length));
}
}
解决方案
您需要先转换为 int,然后再转换为字符串:
double doubleNum = 1000.00;
int intNum = d.toInt();
yourValue = intNum.toString();
或单行:
String value= 1000.00.toInt().toString();
您可以编写 var 来获取您的值而不是 1000.00。
推荐阅读
- asp.net-mvc - 如何使用实体框架将基类转换为派生类
- python - 如何添加复制某些列的新行,但在其他列中分配新值
- flutter - 颤动中自动扩展容器——适用于所有设备
- javascript - div onclick 不触发(css 动画箭头,可能的 div 大小/覆盖问题)
- javascript - 如何在从一个域重定向到另一个域时将数据传递到另一个域
- python - OneHotEncoder 更改名称列
- hive - 如何正确设置 SerDe XML 架构?
- powerbi - 基于 Power Bi 中的多个切片器计算结果行的数量
- hdbscan - 如何在 HDBSCAN 中打印输出结果
- jquery - 需要从组中选中 4 个复选框