Last active
March 10, 2025 15:54
-
-
Save ArefMozafari/b553afdbcd44c71e5e0e35fe75494840 to your computer and use it in GitHub Desktop.
Flutter/Dart - How to add commas to a string number after each three digit
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
import 'package:flutter/services.dart'; | |
import 'package:intl/intl.dart'; | |
class NumericTextFormatter extends TextInputFormatter { | |
@override | |
TextEditingValue formatEditUpdate( | |
TextEditingValue oldValue, TextEditingValue newValue) { | |
if (newValue.text.isEmpty) { | |
return newValue.copyWith(text: ''); | |
} else if (newValue.text.compareTo(oldValue.text) != 0) { | |
final int selectionIndexFromTheRight = | |
newValue.text.length - newValue.selection.end; | |
final f = NumberFormat("#,###"); | |
final number = | |
int.parse(newValue.text.replaceAll(f.symbols.GROUP_SEP, '')); | |
final newString = f.format(number); | |
return TextEditingValue( | |
text: newString, | |
selection: TextSelection.collapsed( | |
offset: newString.length - selectionIndexFromTheRight), | |
); | |
} else { | |
return newValue; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment