flutter - 在 Flutter 输入中将值转换为数字格式?
问题描述
我对 Flutter InputTextField 有疑问。我正在开发一个像 CashApp 这样的应用程序,如果你有一个可以向其他人汇款的功能。
问题是:我需要实现数字格式并且只允许两位小数。
例如,如果我输入:
"1000,25" -> 需要转换为 1.000,25
"10000,25" -> 需要转换为 10.000,25
等等..
我一直在使用此代码来达到唯一的两位小数部分
import 'package:flutter/services.dart';
import 'dart:math' as math;
class DecimalTextInputFormatter extends TextInputFormatter {
DecimalTextInputFormatter({this.decimalRange, this.activatedNegativeValues})
: assert(decimalRange == null || decimalRange >= 0,
'DecimalTextInputFormatter declaretion error');
final int decimalRange;
final bool activatedNegativeValues;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, // unused.
TextEditingValue newValue,
) {
TextSelection newSelection = newValue.selection;
String truncated = newValue.text;
if (newValue.text.contains(' ')) {
return oldValue;
}
if (newValue.text.isEmpty) {
return newValue;
} else if (double.tryParse(newValue.text) == null &&
!(newValue.text.length == 1 &&
(activatedNegativeValues == true ||
activatedNegativeValues == null) &&
newValue.text == '-')) {
return oldValue;
}
if (activatedNegativeValues == false &&
double.tryParse(newValue.text) < 0) {
return oldValue;
}
if (decimalRange != null) {
String value = newValue.text;
if (decimalRange == 0 && value.contains(".")) {
truncated = oldValue.text;
newSelection = oldValue.selection;
}
if (value.contains(".") &&
value.substring(value.indexOf(".") + 1).length > decimalRange) {
truncated = oldValue.text;
newSelection = oldValue.selection;
} else if (value == ".") {
truncated = "0.";
newSelection = newValue.selection.copyWith(
baseOffset: math.min(truncated.length, truncated.length + 1),
extentOffset: math.min(truncated.length, truncated.length + 1),
);
}
return TextEditingValue(
text: truncated,
selection: newSelection,
composing: TextRange.empty,
);
}
return newValue;
}
}
这是我从这篇文章中找到的回复
这段代码几乎可以做到这一点。它限制了两位小数部分,但没有 NumberFormat 部分,并且使用“点”代替小数的“逗号”。
我想交换'。千位,',' 代表小数。并添加 NumberFormat 。
有什么办法可以做到这一点?
解决方案
这是巴西的语言环境吗?然后可以在 DecimalTextInputFormatter 类中设置巴西的数字货币格式以达到相同的结果。
推荐阅读
- ietf-netmod-yang - config=false 强制节点
- elm - 在 Elm 中组合两个不同的 API 请求
- python - 如果 Python 中不存在 For 循环迭代,则获取空值
- ios - Xcode 能源影响非常高 - iPhone X 上的显示
- mysql - 如何在 group_concat 函数 MYSQL 中使用换行符作为分隔符?
- javascript - 如何从三个函数中获取值到外部并实时更新?
- excel - 测试字符串是否包含子字符串
- python - 模块对象没有来自 docker 容器的属性 windll
- javascript - 按钮上的 React onBlur 事件在 Safari 中不起作用
- jquery - 如何在 $.post 中隐藏表单操作或 URL