toPrice function
String
toPrice(
- dynamic cents, {
- bool showPlus = false,
- bool isNegative = false,
- String? symbol = "\$",
- int decimalDigits = 2,
- double divider = 100,
- bool removeTrailingZeros = false,
})
Implementation
String toPrice(
dynamic cents, {
bool showPlus = false,
bool isNegative = false,
String? symbol = "\$",
int decimalDigits = 2,
/// 1 if is dollar, 100 if is cent
double divider = 100,
bool removeTrailingZeros = false,
}) {
if (cents != null) {
dynamic val = cents;
if (cents is String) {
val = double.tryParse(cents);
}
if (val is num) {
final bool trueNegative = isNegative || (val < 0);
String dollarResult = (divider > 1 ? (val / divider) : val)
.abs()
.toDouble()
.toStringAsFixed(decimalDigits);
List<String> dollarParts = dollarResult.split('.');
dollarParts[0] = dollarParts[0].replaceAllMapped(
RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
(Match match) => '${match[1]},',
);
dollarResult = dollarParts.join('.');
if (removeTrailingZeros && dollarResult != '0') {
if (dollarResult.endsWith('.00')) {
dollarResult = dollarResult.substring(0, dollarResult.length - 3);
} else if (dollarResult.endsWith('0')) {
dollarResult = dollarResult.substring(0, dollarResult.length - 1);
}
}
if (symbol?.isNotEmpty ?? false) {
dollarResult = "$symbol$dollarResult";
}
if (trueNegative) {
dollarResult = "-$dollarResult";
} else if (showPlus) {
dollarResult = "+$dollarResult";
}
// String result = NumberFormat.currency(
// symbol: symbol,
// decimalDigits: decimalDigits,
// ).format(val / 100);
// if (isNegative && val > 0) {
// result = "-$result";
// } else if (showPlus && val >= 0) {
// result = "+$result";
// }
// if (removeTrailingZeros) {
// if (result == '0') return '0';
// if (result.endsWith('.00')) {
// return result.substring(0, result.length - 3);
// }
// if (result.endsWith('0')) return result.substring(0, result.length - 1);
// }
return dollarResult;
}
}
return "\$-";
}