Created
March 25, 2024 18:54
-
-
Save unacorbatanegra/72873937a5b89096e2f833e7882c3773 to your computer and use it in GitHub Desktop.
CommaTextInputFormatter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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