Skip to content

Instantly share code, notes, and snippets.

@unacorbatanegra
Created March 25, 2024 18:54
Show Gist options
  • Save unacorbatanegra/72873937a5b89096e2f833e7882c3773 to your computer and use it in GitHub Desktop.
Save unacorbatanegra/72873937a5b89096e2f833e7882c3773 to your computer and use it in GitHub Desktop.
CommaTextInputFormatter
extension PriceFormat on num? {
static final f = NumberFormat("###,###,##0.##", "en_US");
String get format => formatter.format(this);
String get simpleFormat => f.format(this);
}
class CommaTextInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
if (newValue.text.isEmpty) return newValue;
var n = newValue.text.replaceAll(',', '');
var text = '';
if (n.startsWith('0.')) {
double value;
try {
value = PriceFormat.f.parse(n).toDouble();
} on FormatException {
value = 0.0;
}
text = value.simpleFormat;
}
if (n.startsWith('.')) {
if (n.length > 1) {
final value = PriceFormat.f.parse('0.' + n);
text = value.simpleFormat;
} else {
text = n;
}
} else if (n.endsWith('.')) {
final value = PriceFormat.f.parse(n.replaceAll('.', ''));
text = value.simpleFormat + '.';
} else {
final value = PriceFormat.f.parse(n);
text = value.simpleFormat;
}
return TextEditingValue(
text: text,
selection: TextSelection.collapsed(
offset: text.length,
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment