在dart和flutter中有没有更好的方法给int加上前导零

dy1byipe  于 2023-10-22  发布在  Flutter
关注(0)|答案(2)|浏览(135)

我为dart int创建了一个扩展来添加前导零,我想知道是否有更优雅的方法?我对它的看法:

extension IntExtensions on int {
  ///returns a String with leading zeros.
  ///1 would be with the [numberOfTotalDigits] = 3 lead to a string '001'
  String addLeadingZeros(int numberOfTotalDigits) {
    var valueAsString = this.toString();
    var buffer = StringBuffer();
    if (valueAsString.length < numberOfTotalDigits) {
      var addLeadingZeros = numberOfTotalDigits - valueAsString.length;
      for (int i = 0; i < addLeadingZeros; i++) buffer.write('0');
    }
    return '${buffer.toString()}$valueAsString';
  }
}

单元测试:

import 'package:flutter_test/flutter_test.dart';
import 'package:utilities/extensions/int_extensions.dart';

void main() {
  test('test addLeadingZeros int extension', () {
    int a = 1;
    expect(a.addLeadingZeros(5), equals('00001'));
    expect(a.addLeadingZeros(1), equals('1'));
    expect(a.addLeadingZeros(2), equals('01'));
    expect(a.addLeadingZeros(3), equals('001'));
    expect(a.addLeadingZeros(0), equals('1'));
  });
}
sczxawaw

sczxawaw1#

像这样?

extension IntExtensions on int {
  ///returns a String with leading zeros.
  ///1 would be with the [numberOfTotalDigits] = 3 lead to a string '001'
  String addLeadingZeros(int numberOfTotalDigits) =>
      toString().padLeft(numberOfTotalDigits, '0');
}
qij5mzcb

qij5mzcb2#

如何在左边的数字中添加前导零:

String number = "345";
String number2 = "345345";

String numbera = number.padLeft(10, "0");
print(numbera); //Output: 0000000345

String numberb = number2.padLeft(10, "0");
print(numberb); //Output: 0000345345

在这里,number和number2字符串有不同的长度,但是使用padLeft(),你可以用前导零来创建相同长度的字符串。您还可以将零替换为任何其他字符,以添加到任何字符串的前导处,例如:

String number2 = "345345";

String numberc = number2.padLeft(10, "R");
print(numberc); //Output: RRRR345345

在这里,我们附加了其他字符而不是零。
如何在字符串的右侧附加字符:

String number2 = "345345";

String numberd = number2.padRight(10, "D");
print(numberd); //output: 345345DDDD

在这里,我们在字符串的右侧附加了“D”,以满足其长度为10。

相关问题