Home > other >  Slicing characters from string (flutter)
Slicing characters from string (flutter)

Time:06-03

When a number is longer than 4 or more characters, I want to replace the last number(s) with 'k'. The final value should also be converted to a string. TIA!

CodePudding user response:

final value = 54325342534.toString();
  print(value.replaceRange(3, value.length, 'k' * (value.length - 3)));

CodePudding user response:

You can do this using the Right Pad concept with padRight method in the String class:

Example:

String formatNumber(int number) {
  final numberAsString = number.toString();
  return numberAsString.substring(0, 4).padRight(numberAsString.length, 'k');
}

And use it like the following, let's try the value 123456789:

void main() {
  final number = 123456789;
  print(formatNumber(number));
}

Output:

1234kkkkk
  • Related