Last active
July 19, 2022 16:19
-
-
Save Teemwu/ff8344d905e665f3f256ba76bd04eb4d to your computer and use it in GitHub Desktop.
Dart utils
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
class Format { | |
/// 将数字转换成 'k' 结尾的字符串 | |
/// https://stackoverflow.com/a/9462382 | |
static nFormatter(dynamic num, [int digits=1]) { | |
var si = [ | |
{'value': 1, 'symbol': ''}, | |
{'value': 1e3, 'symbol': 'k'}, | |
{'value': 1e6, 'symbol': 'M'}, | |
{'value': 1e9, 'symbol': 'G'}, | |
{'value': 1e12, 'symbol': 'T'}, | |
{'value': 1e15, 'symbol': 'P'}, | |
{'value': 1e18, 'symbol': 'E'}, | |
]; | |
var rx = RegExp(r'\.0+$|(\.[0-9]*[1-9])0+$'); | |
var i; | |
for (i = si.length - 1; i > 0; i--) { | |
if (num.abs() >= si[i]['value']) { | |
break; | |
} | |
} | |
return (num / si[i]['value']).toStringAsFixed(digits).replaceAll(rx, '') + si[i]['symbol']; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment