将数字转换为Dart中的人类可读格式(例如1.5k,5m,1b)?

May*_*ati 2 dart flutter

我正在开发与社交聊天相关的应用程序,我想将大数字转换为人类可读的格式(例如1500到1.5k),而且我还是Dart的新手。您的帮助将不胜感激。

Ami*_*gid 7

您可以使用Flutter的NumberFormat类,该类具有一些内置函数,可用于所需的结果。

查看此链接了解Flutter的NumberFormat类

示例:这是您要使用货币的一种方法。

var _formattedNumber = NumberFormat.compactCurrency(
  decimalDigits: 2,
  symbol: '', // if you want to add currency symbol then pass that in this else leave it empty.
).format(numberToFormat);

print('Formatted Number is $numberToFormat');
Run Code Online (Sandbox Code Playgroud)

代码的输出为:

如果输入1000,则输出1K

另一种方法是仅使用NumberFormat.compact()给出所需的输出...

// In this you won't have to worry about the symbol of the currency.
var _formattedNumber = NumberFormat.compact().format(numberToFormat);
print('Formatted Number is $numberToFormat');
Run Code Online (Sandbox Code Playgroud)

上面示例的输出也将是:

如果输入1000,则输出1K

我尝试了这个并且正在工作...

  • 是的,也可以做到……但这给出了完整的字符串,而不仅仅是 M 代表百万,K 代表千…… (2认同)