formatCurrency Function
A custom function to format a number as currency in FlutterFlow
Formatting
formatCurrency - Format Number as Currency
Converts a number into a formatted currency string. This function allows you to specify the currency symbol, decimal places, and whether to use comma separators.
Function Output:
String - The formatted currency string.
Function Inputs:
- amount: double
- Description: The number to be formatted as currency.
- symbol: String (optional, default: ’$’)
- Description: The currency symbol to be used.
- decimalPlaces: int (optional, default: 2)
- Description: The number of decimal places to show.
- useCommas: bool (optional, default: true)
- Description: Whether to use comma separators for thousands.
Example Usage:
Scenario: Formatting product prices in an e-commerce app.
Input: amount: 1234.56, symbol: ’€’, decimalPlaces: 2, useCommas: true Output: The formatted currency string
String formattedPrice = formatCurrency(1234.56, symbol: '€', decimalPlaces: 2, useCommas: true);
print(formattedPrice); // Output: €1,234.56
Result:
"€1,234.56"
Source Code:
String symbol = '\$'; int decimalPlaces = 2; bool useCommas = true; String result = symbol; if (useCommas) { result += NumberFormat('#,##0', 'en_US').format(amount.truncate()); } else { result += amount.truncate().toString(); } if (decimalPlaces > 0) { result += '.${amount.toStringAsFixed(decimalPlaces).split('.')[1]}'; } return result;
Formatted Function:
```dart
String formatCurrency(double amount, {String symbol = '\$', int decimalPlaces = 2, bool useCommas = true}) {
String result = symbol;
if (useCommas) { result += NumberFormat(’#,##0’, ‘en_US’).format(amount.truncate()); } else { result += amount.truncate().toString(); }
if (decimalPlaces > 0) { result += ’.${amount.toStringAsFixed(decimalPlaces).split(’.’)[1]}’; }
return result; }
</div>
## Source Code Image:
