toGrouped method

String toGrouped([
  1. String separator = ','
])

Convert to a grouped string (e.g. 1234567 -> 1,234,567).

  • separator: the separator between each group. should be a single character.

Example

12345678.toGrouped();  // "12,345,678"
12345678.toGrouped('-');  // "12-345-678"
12345678.toGrouped('\'');  // "12'345'678"

Implementation

String toGrouped([String separator = ',']) {
  assert(separator.length == 1, 'separator must be a single character');

  final str = toString();
  RegExp reg = RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
  return str.replaceAllMapped(reg, (Match match) => '${match[1]}$separator');
}