首页 > 解决方案 > 格式化没有小数点的文本输入字段

问题描述

我试图在 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));
  }
}

标签: flutterdartformatting

解决方案


您需要先转换为 int,然后再转换为字符串:

double doubleNum = 1000.00;
int intNum = d.toInt();
yourValue = intNum.toString();

或单行:

String value= 1000.00.toInt().toString();

您可以编写 var 来获取您的值而不是 1000.00。


推荐阅读