flutter 如何在 dart 中将数字格式化为千位分隔符

44u64gxh  于 2023-02-09  发布在  Flutter
关注(0)|答案(7)|浏览(1051)

我必须在dart中将数字格式化为千位分隔符。我有这样的数字:

16987

13876

456786

我想把它们格式化为:

16,987

13,876 

4,56,786
mqkwyuun

mqkwyuun1#

您可以使用NumberFormat在ICU格式模式中传递自定义格式,请参阅NumberFormat

import 'package:intl/intl.dart';

void main() {
  var formatter = NumberFormat('#,##,000');
  print(formatter.format(16987));
  print(formatter.format(13876));
  print(formatter.format(456786));
}

产出

16,987
13,876
4,56,786
vatpfxk5

vatpfxk52#

我发现intl包中的NumberFormat类非常有用,因为它提供了不同的数字格式化方法。
默认情况下,NumberFormat类使用默认的美国语言环境格式化以百万为单位的数字,我们可以使用印度语言环境格式化以千为单位的数字(它可以根据任何国家的语言环境格式化数字或货币)。NumberFormat.decimalPattern([String locale])

import 'package:intl/intl.dart';   

void main() {
  NumberFormat numberFormat = NumberFormat.decimalPattern('hi');
  print(numberFormat.format(16987));
  print(numberFormat.format(13876));
  print(numberFormat.format(456786));
}

产出

16,987
13,876
4,56,786
ecfdbz9o

ecfdbz9o3#

你不需要使用NumberFormat软件包就可以做到这一点。这应该会有帮助,用任何数字测试它。

String formatAmount(){
    String price = "1000000000";
    String priceInText = "";
    int counter = 0;
    for(int i = (price.length - 1);  i >= 0; i--){
        counter++;
        String str = price[i];
        if((counter % 3) != 0 && i !=0){
          priceInText = "$str$priceInText";
        }else if(i == 0 ){
          priceInText = "$str$priceInText";
        
        }else{
          priceInText = ",$str$priceInText";
        }
    }
    return priceInText.trim();
  }

然后,您可以通过打印来使用:

print(formatAmount());

输出:

1,000,000,000
eqfvzcg8

eqfvzcg84#

您可以使用此更灵活的扩展:

/// Return as number as formatted in thousands string.
/// Example: -123456.asThousands() returns -123'456
String asThousands({
  final String separator = "'",
  final int digits = 3,
}) {
  assert(digits >= 1, '5d40ef0f-f8b4-4070-adf4-bbfc1a8b663b');
  final chars =
      abs().truncate().toString().split(StringHelper.empty).reversed;
  var n = 0;
  var result = StringHelper.empty;
  for (final ch in chars) {
    if (n == digits) {
      result = '$ch$separator$result';
      n = 1;
    } else {
      result = '$ch$result';
      n++;
    }
  }
  result = this < 0 ? '-$result' : result;
  result = (this is double)
      ? '$result${toString().substring(toString().lastIndexOf('.'))}'
      : result;
  return result;
}

示例调用:

test('Test NumHelper.asThousands()', () {
  expect(
    123456789.asThousands(separator: StringHelper.space),
    '123 456 789',
  );
  expect(123456789.asThousands(separator: ','), '123,456,789');
  expect(
    123456789.asThousands(separator: ',', digits: 2),
    '1,23,45,67,89',
  );
  expect((-123456789).asThousands(separator: ','), '-123,456,789');
  expect((-123456).asThousands(separator: ','), '-123,456');
  expect((-12345).asThousands(separator: ','), '-12,345');
  expect(1.asThousands(), '1');
  expect(12.asThousands(), '12');
  expect(123.asThousands(), '123');
  expect(1995.asThousands(), "1'995");
  expect(12345678.asThousands(), "12'345'678");
  expect((-123456789.123).asThousands(separator: ','), '-123,456,789.123');
});
5m1hhzi4

5m1hhzi45#

该活动的伪代码如下所示:

Here, `string` is an input string with indexes starting at 0.
let i = (length of string) - 3
while i > 0 do
    insert a "," into string at position (i)
    let i = i - 3
return string

Dart代码

extension on int {
  String get priceString {
    final numberString = toString();
    final numberDigits = List.from(numberString.split(''));
    int index = numberDigits.length - 3;
    while (index > 0) {
      numberDigits.insert(index, ',');
      index -= 3;
    }
    return numberDigits.join();
  }
}
rsl1atfo

rsl1atfo6#

如果你想用千位分隔符格式化一个数字,并给它一个十进制数的最大值。

var formatter = NumberFormat('#,##0.' + "#" * 5); 

print(formatter.format(double.parse('1000.456781234'.replaceAll(",", ""))));

OUTPUT: 1,000.45678

希望这对你有帮助

7eumitmz

7eumitmz7#

这里最简单的方法是使用intl中的NumberFormat类,请按照给定的步骤操作。
将此软件包添加到您的pubspec.yaml

dependencies:
  intl: ^0.17.0

在dart扩展文件中使用下面这行代码

final numberFormat = NumberFormat.decimalPattern('hi');

extension ExtOnNum on num {
  format() {
    final parts = toString().split('.');
    return '${numberFormat.format(num.tryParse(parts[0]) ?? 0.0)}.${parts[1]}';
  }
}

输出:

print(5843.41.format());

5,843.41

相关问题