I recently came across your solution on Stack Overflow for formatting numbers in a readable way, and I wanted to thank you for sharing it. I implemented it in my project and it worked perfectly.
However, while working with the solution, I realized it could be made a bit more convenient and portable for use throughout the entire project without having to export the function every time it's needed. That's why I decided to encapsulate it within a Dart extension.
I created an extension called FinantialFormat
that contains the formatToFinancial
method, which accepts an optional parameter to include the money symbol if needed. This way, I can now easily use this functionality anywhere in the project simply by calling formatToFinancial()
on a string.
Of course, I want to give you full credit for the original solution. Your approach was very helpful, and I simply tried to improve the way of using it in my project.
If you have any suggestions or comments regarding this, I'd be happy to hear them!
extension FinancialFormat on String {
String mathFunc(Match match) => '${match[1]},';
String formatToFinancial({
bool isMoneySymbol = false,
}) {
final RegExp reg = RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
final formatNumber = replaceAllMapped(reg, mathFunc);
if (isMoneySymbol) {
return '\$ $formatNumber';
}
return formatNumber;
}
}
Example to use it:
TitleH1(
text: bank!.amount.toString().formatToFinancial(
isMoneySymbol: true,
),
color: colorScheme.onBackground,
fontSize: 30.0,
),
$&,
replacer. It's for JS only, without this replacer expression doesn't work. We should change expression to a little, look at my answer bellow. – Heteronym