Last active
July 24, 2024 06:41
-
-
Save lopo12123/f7d87e05f90d43eed76feaee75d821b1 to your computer and use it in GitHub Desktop.
BadFL Example Code (extension/num)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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