gpt4 book ai didi

dart - 如何转换大数以缩短 Dart 中的 K/M/B

转载 作者:行者123 更新时间:2023-12-03 04:12:00 25 4
gpt4 key购买 nike

如何在 Dart 中创建将大数转换为带字符的短数的函数?

喜欢

1000 => 1K
10000 => 10K
1000000 => 1M
10000000 => 10M
1000000000 => 1B

最佳答案

Dart中有一个内置函数可以使用,而且很简单:

var f = NumberFormat.compact(locale: "en_IN");
print(f.format(12345));

让它成为一个方法:

getShortForm(var number) {
var f = NumberFormat.compact(locale: "en_US");
return f.format(number);
}

为此导入

import 'package:intl/intl.dart';

有关更多信息,请参阅此文档 https://pub.dev/documentation/intl/latest/intl/NumberFormat-class.html

如果你正在寻找困难的方法:

getShortForm(int number) {
var shortForm = "";
if (number != null) {
if (number < 1000) {
shortForm = number.toString();
} else if (number >= 1000 && number < 1000000) {
shortForm = (number / 1000).toStringAsFixed(1) + "K";
} else if (number >= 1000000 && number < 1000000000) {
shortForm = (number / 1000000).toStringAsFixed(1) + "M";
} else if (number >= 1000000000 && number < 1000000000000) {
shortForm = (number / 1000000000).toStringAsFixed(1) + "B";
}
}
return shortForm;
}

关于dart - 如何转换大数以缩短 Dart 中的 K/M/B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52661247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com