amountFormat static method
Format number with thousand separators
Formats numbers with comma separators every 3 digits and handles decimals
value The value to format (can be num, int, double, or String)
digit Number of decimal places to show (default: 0)
Example:
NumberUtils.amountFormat(1234567); // Returns: '1,234,567'
NumberUtils.amountFormat(1234567.89, digit: 2); // Returns: '1,234,567.89'
NumberUtils.amountFormat('9999.5', digit: 2); // Returns: '9,999.50'
NumberUtils.amountFormat(1000); // Returns: '1,000'
Implementation
static String amountFormat(dynamic value, {int digit = 0}) {
// Convert value to string
String stringValue = value.toString();
// Check if it has decimals
bool hasDecimals = stringValue.contains('.') &&
(double.tryParse(stringValue) ?? 0) % 1 != 0;
double number = double.tryParse(stringValue) ?? 0;
// Set decimal places
String fixed =
hasDecimals ? number.toStringAsFixed(digit) : number.toStringAsFixed(0);
// Split integer and decimal parts
List<String> parts = fixed.split('.');
String integerPart = parts[0];
String decimalPart = parts.length > 1 ? parts[1] : "";
// Add thousand separators to integer part
String formattedInt = integerPart.replaceAllMapped(
RegExp(r'(\d)(?=(\d{3})+(?!\d))'),
(Match m) => "${m[1]},",
);
// Combine result
return hasDecimals && decimalPart.isNotEmpty
? "$formattedInt.$decimalPart"
: formattedInt;
}