I am getting a String balance from the backend, and it is something like this 430000. I would like to have an output like this 430,000. How do I go about it?
Row(
children: [
Padding(
padding: const EdgeInsets.only(
left: 12,
),
child: Text(
"₦ ${user.availableBalance.toStringAsFixed(0)} ",
style: TextStyle(
color: Colors.white,
fontSize: 21.sp,
),
)),
],
),
CodePudding user response:
The best way is to use Regex
so define this on the top
class _HomeTabState extends State<HomeTab> {
//Regex
RegExp reg = RegExp(r'(\d{1,3})(?=(\d{3}) (?!\d))'); //immport dar:core
RegExp regex = RegExp(r'([.]*0)(?!.*\d)');
String Function(Match) mathFunc = (Match match) => '${match[1]},'; //match
...
//In your build
Widget build(BuildContext context) {
...
Row(
children: [
Padding(
padding: const EdgeInsets.only(
left: 12,
),
child: Text(
"₦ ${double.parse(user.availableBalance.toString()).toStringAsFixed(0)} " .replaceAllMapped(
reg, mathFunc),
style: TextStyle(
color: Colors.white,
fontSize: 21.sp,
),
)),
],
),
...
}
}
Then to use it just turn your balance into a double then to String in order to access the toStringAsFixed(0)
like this
"${double.parse(balance.toString()).toStringAsFixed(0)}".replaceAllMapped(reg, mathFunc),
so for 430 -> would be 430 and 4300 -> would be 4,300 and 43000 -> would be 43,000
CodePudding user response:
I would suggest using the intl
package https://pub.dev/packages/intl
Example usage:
var f = NumberFormat("#,###.##");
print(f.format(123456789.4567));
This will result in the following output:
123,456,789.46
Note that ,
in the pattern specifies the grouping separator and ###
specifies the group size to be 3. .##
specifies rounding on two decimal points.
Check for additional documentation: https://api.flutter.dev/flutter/intl/NumberFormat-class.html