Skip to content

Instantly share code, notes, and snippets.

@lopo12123
Last active July 24, 2024 06:41
Show Gist options
  • Save lopo12123/f7d87e05f90d43eed76feaee75d821b1 to your computer and use it in GitHub Desktop.
Save lopo12123/f7d87e05f90d43eed76feaee75d821b1 to your computer and use it in GitHub Desktop.
BadFL Example Code (extension/num)
extension NumExt on num {
String readableFixed([int fractionDigits = 1]) {
final absVal = abs();
String raw = '';
String unit = '';
switch (absVal) {
case < 1e3:
raw = toStringAsFixed(fractionDigits);
break;
case < 1e6:
raw = (this / 1e3).toStringAsFixed(fractionDigits);
unit = 'K';
break;
case < 1e9:
raw = (this / 1e6).toStringAsFixed(fractionDigits);
unit = 'M';
break;
default:
raw = (this / 1e9).toStringAsFixed(fractionDigits);
unit = 'B';
break;
}
final display = raw.replaceAll(RegExp(r'\.?0+$'), '');
return '$display$unit';
}
String get readable => readableFixed();
String get segmented {
String str = toString();
RegExp regExp = RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
return str.replaceAllMapped(regExp, (Match match) => '${match[1]},');
}
}
void main() {
final List<num> nums = [
42,
12345,
99802,
9850024,
10e7,
10e9 + 500,
];
for (num n in nums) {
print('number: ${n.readable}');
print('readable: ${n.readable}');
print('segmented: ${n.segmented}\n');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment