| 1 | import 'package:cw_core/amount/amount_sanitizer.dart'; |
| 2 | |
| 3 | String calculateFiatAmount({double? price, String? cryptoAmount, bool raw = false}) { |
| 4 | if (price == null || cryptoAmount == null) { |
| 5 | return '0.00'; |
| 6 | } |
| 7 | |
| 8 | cryptoAmount = cryptoAmount.sanitized(); |
| 9 | |
| 10 | final _amount = double.tryParse(cryptoAmount); |
| 11 | if (_amount == null || _amount.isNaN) return '0.00'; |
| 12 | final _result = price * _amount; |
| 13 | final result = _result < 0 ? _result * -1 : _result; |
| 14 | |
| 15 | if (result == 0.0) { |
| 16 | return '0.00'; |
| 17 | } |
| 18 | |
| 19 | if (raw) { |
| 20 | return result.toStringAsFixed(2); |
| 21 | } |
| 22 | |
| 23 | var formatted = ''; |
| 24 | final parts = result.toString().split('.'); |
| 25 | |
| 26 | if (parts.length >= 2) { |
| 27 | if (parts[1].length > 2) { |
| 28 | formatted = formatWithCommas(parts[0] + '.' + parts[1].substring(0, 2)); |
| 29 | } else { |
| 30 | formatted = formatWithCommas(parts[0] + '.' + parts[1]); |
| 31 | } |
| 32 | } else { |
| 33 | formatted = formatWithCommas(parts[0]); |
| 34 | } |
| 35 | |
| 36 | return result > 0.01 ? formatted : '< 0.01'; |
| 37 | } |
| 38 | |
| 39 | String formatWithCommas(String? number) { |
| 40 | if (number?.isEmpty ?? true) return ''; |
| 41 | |
| 42 | final parts = number!.split('.'); |
| 43 | final integerPart = parts[0]; |
| 44 | var decimalPart = parts.length > 1 ? parts[1] : ''; |
| 45 | |
| 46 | final formattedInteger = integerPart.replaceAllMapped( |
| 47 | RegExp(r'\B(?=(\d{3})+(?!\d))'), |
| 48 | (Match match) => ',', |
| 49 | ); |
| 50 | |
| 51 | if (decimalPart.length == 1) { |
| 52 | decimalPart = "${decimalPart}0"; |
| 53 | } |
| 54 | |
| 55 | return decimalPart.isNotEmpty ? '$formattedInteger.$decimalPart' : formattedInteger; |
| 56 | } |