作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在flutter中的TextFormField
中键入数字时,有没有办法制作千位分隔符?
这是我的TextFormField
child: TextFormField(
decoration: InputDecoration(
border: const OutlineInputBorder()),
keyboardType: TextInputType.number,
),
最佳答案
Flutter并没有内置任何东西可以处理这个问题。您将不得不使用自己的自定义文本格式设置。 (源自this answer。)
import 'package:flutter/services.dart';
class ThousandsSeparatorInputFormatter extends TextInputFormatter {
static const separator = ','; // Change this to '.' for other locales
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
// Short-circuit if the new value is empty
if (newValue.text.length == 0) {
return newValue.copyWith(text: '');
}
// Handle "deletion" of separator character
String oldValueText = oldValue.text.replaceAll(separator, '');
String newValueText = newValue.text.replaceAll(separator, '');
if (oldValue.text.endsWith(separator) &&
oldValue.text.length == newValue.text.length + 1) {
newValueText = newValueText.substring(0, newValueText.length - 1);
}
// Only process if the old value and new value are different
if (oldValueText != newValueText) {
int selectionIndex =
newValue.text.length - newValue.selection.extentOffset;
final chars = newValueText.split('');
String newString = '';
for (int i = chars.length - 1; i >= 0; i--) {
if ((chars.length - 1 - i) % 3 == 0 && i != chars.length - 1)
newString = separator + newString;
newString = chars[i] + newString;
}
return TextEditingValue(
text: newString.toString(),
selection: TextSelection.collapsed(
offset: newString.length - selectionIndex,
),
);
}
// If the new value and old value are the same, just return as-is
return newValue;
}
}
用法:
TextField(
decoration: InputDecoration(
border: const OutlineInputBorder(),
),
keyboardType: TextInputType.number,
inputFormatters: [ThousandsSeparatorInputFormatter()],
),
示例:
https://codepen.io/Abion47/pen/mdVLgGP
关于flutter - flutter 中的千位分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62821439/
我正在使用报表查看器控件 (rdlc) 生成报表。我的一列表示来自 SQL 数据库的十进制值,例如: 5199.9800 在此列的末尾,汇总了所有金额。因此,金额行以这种方式表示: =Fields!
我在这段代码中尝试用以下模式替换引号 (') 的千位分隔符 (.):###'###,## import java.text.*; public class NumberFormatTests
对于具有财务计算的网站,我尝试将包含在 HTML 输入字段中的每个数字转换为 xxx,xxx,xxx.xx 格式,其中千位分隔符为逗号,小数点为小数点。与我们从 Excel 中了解到的类似。 现在是挑
有没有一种方法可以使用字符串格式化程序将 Thousands、Millions、Billions 格式化为 123K、123M、123B 而无需更改代码以将值除以 Thousand、Million 或
我是一名优秀的程序员,十分优秀!