Advertisement
virtuoso_o

formatter

Mar 9th, 2023
774
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 1.70 KB | None | 0 0
  1. class DecimalFormatter extends TextInputFormatter {
  2.   final int decimalDigits;
  3.  
  4.   DecimalFormatter({this.decimalDigits = 2}) : assert(decimalDigits >= 0);
  5.  
  6.   @override
  7.   TextEditingValue formatEditUpdate(
  8.     TextEditingValue oldValue,
  9.     TextEditingValue newValue,
  10.   ) {
  11.     String newText;
  12.  
  13.     if (decimalDigits == 0) {
  14.       newText = newValue.text.replaceAll(RegExp('[^0-9]'), '');
  15.     } else {
  16.       newText = newValue.text.replaceAll(RegExp('[^0-9\.]'), '');
  17.     }
  18.  
  19.     if (newText.contains('.')) {
  20.       //in case if user's first input is "."
  21.       if (newText.trim() == '.') {
  22.         return newValue.copyWith(
  23.           text: '0.',
  24.           selection: const TextSelection.collapsed(offset: 2),
  25.         );
  26.       }
  27.       //in case if user tries to input multiple "."s or tries to input
  28.       //more than the decimal place
  29.       else if ((newText.split(".").length > 2) ||
  30.           (newText.split(".")[1].length > decimalDigits)) {
  31.         return oldValue;
  32.       } else {
  33.         return newValue;
  34.       }
  35.     }
  36.  
  37.     //in case if input is empty or zero
  38.     if (newText.trim() == '' || newText.trim() == '0') {
  39.       return newValue.copyWith(text: '');
  40.     } else if (int.parse(newText) < 1) {
  41.       return newValue.copyWith(text: '');
  42.     }
  43.  
  44.     double newDouble = double.parse(newText);
  45.     var selectionIndexFromTheRight =
  46.         newValue.text.length - newValue.selection.end;
  47.  
  48.     String newString = NumberFormat("#,##0.##").format(newDouble);
  49.     // String formattedString = "$newString.00";
  50.     return TextEditingValue(
  51.       text: newString,
  52.       selection: TextSelection.collapsed(
  53.         offset: newString.length - selectionIndexFromTheRight,
  54.       ),
  55.     );
  56.   }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement