-
Notifications
You must be signed in to change notification settings - Fork 0
/
num.dart
38 lines (33 loc) · 974 Bytes
/
num.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
extension NumExt on num {
/// to readable string with fixed fraction digits
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]},');
}
}