uaestats_fe/lib/infrastructure/services/packages/num_abbreviation.dart
2026-05-16 11:31:32 +05:30

56 lines
1.6 KiB
Dart
Executable File

import 'dart:math';
import 'package:intl/intl.dart';
extension Abbreviation on num {
/// adds "k" for thousand, "m" for
/// million, "b" for billion, "t"
/// for trillion
String toAbbreviatedString() {
final zerothPowerToSuffix = {
15: 'qd',
12: 't',
9: 'b',
6: 'm',
3: 'k',
};
for (int i = 0; i < zerothPowerToSuffix.length; i++) {
final pair = zerothPowerToSuffix.entries.elementAt(i);
final threshold = pow(10, pair.key);
if (abs() > threshold) {
final n = this / threshold;
final nWithDecimal = n.toStringAsFixed(2);
final nonDecimalPart = nWithDecimal.split('.')[0];
final decimalPart = nWithDecimal.split('.')[1];
final end = decimalPart == '00'
? ''
: decimalPart[1] == '0'
? decimalPart[0]
: decimalPart;
final nWithRationalizedDecimals =
nonDecimalPart + (end.isEmpty ? '' : '.$end');
final suffix = pair.value.toUpperCase();
return nWithRationalizedDecimals + suffix;
}
}
return toStringAsFixed(2);
}
String toStringWithCommas({
bool hideDecimals = false,
int? abbreviateIfAbove10powN,
}) {
if (abbreviateIfAbove10powN != null) {
final comparator = pow(10, abbreviateIfAbove10powN);
if (this > comparator) return toAbbreviatedString();
}
final formatter = NumberFormat(
hideDecimals ? '#,###' : '#,##0.##',
);
return formatter.format(this);
}
double pctDifferenceFrom(num n) => 100 * (n - this) / this;
double asPctOf(num n) => 100 * this / n;
}