mirror of
https://github.com/Such-Software/hash-wallet.git
synced 2026-11-07 08:04:04 +01:00
Upstream reformatted its whole tree in 16ddc0837. Matching it removes
formatting from the conflict surface of this and every later sync.
58 lines
1.5 KiB
Dart
58 lines
1.5 KiB
Dart
import 'package:cw_core/amount/amount_sanitizer.dart';
|
|
|
|
String calculateFiatAmount({double? price, String? cryptoAmount, bool raw = false}) {
|
|
if (price == null || cryptoAmount == null) {
|
|
return '0.00';
|
|
}
|
|
|
|
cryptoAmount = cryptoAmount.sanitized();
|
|
|
|
final _amount = double.tryParse(cryptoAmount);
|
|
if (_amount == null || !_amount.isFinite) return '0.00';
|
|
final _result = price * _amount;
|
|
if (!_result.isFinite) return '0.00';
|
|
final result = _result < 0 ? _result * -1 : _result;
|
|
|
|
if (result == 0.0) {
|
|
return '0.00';
|
|
}
|
|
|
|
if (raw) {
|
|
return result.toStringAsFixed(2);
|
|
}
|
|
|
|
var formatted = '';
|
|
final parts = result.toString().split('.');
|
|
|
|
if (parts.length >= 2) {
|
|
if (parts[1].length > 2) {
|
|
formatted = formatWithCommas(parts[0] + '.' + parts[1].substring(0, 2));
|
|
} else {
|
|
formatted = formatWithCommas(parts[0] + '.' + parts[1]);
|
|
}
|
|
} else {
|
|
formatted = formatWithCommas(parts[0]);
|
|
}
|
|
|
|
return result > 0.01 ? formatted : '< 0.01';
|
|
}
|
|
|
|
String formatWithCommas(String? number) {
|
|
if (number?.isEmpty ?? true) return '';
|
|
|
|
final parts = number!.split('.');
|
|
final integerPart = parts[0];
|
|
var decimalPart = parts.length > 1 ? parts[1] : '';
|
|
|
|
final formattedInteger = integerPart.replaceAllMapped(
|
|
RegExp(r'\B(?=(\d{3})+(?!\d))'),
|
|
(Match match) => ',',
|
|
);
|
|
|
|
if (decimalPart.length == 1) {
|
|
decimalPart = "${decimalPart}0";
|
|
}
|
|
|
|
return decimalPart.isNotEmpty ? '$formattedInteger.$decimalPart' : formattedInteger;
|
|
}
|