Flutter Pro Design

Small details that build taste in Flutter.

curated by Kamran BekirovKamran Bekirov

Format numbers for humans

1234567 looks different depending on where your user is:

πŸ‡ΊπŸ‡Έ US: 1,234,567
πŸ‡©πŸ‡ͺ Germany: 1.234.567
πŸ‡«πŸ‡· France: 1 234 567

NumberFormat from the intl package handles that. The simplest case is a plain count, like search results or items in a cart:

// en_US β†’ "1,234,567"
// fr_FR β†’ "1 234 567"
final String count = NumberFormat
    .decimalPatternDigits()
    .format(1234567);

It follows the user's region by default. To force a specific one, pass it in: NumberFormat.decimalPatternDigits(locale: 'de_DE'). And decimalDigits: 2 sets how many digits show after the dot.

Money needs a symbol and the right number of decimals. Give simpleCurrency the currency code and it handles both, even the decimal count (US Dollar has two, Japanese Yen none).

// en_US β†’ "$1,234.50"
// de_DE β†’ "1.234,50 $"
final String price = NumberFormat
    .simpleCurrency(
      name: 'USD',
    )
    .format(1234.50);

Big numbers read better short. compact turns them into K and M:

// "1.23M"
final String views = NumberFormat
    .compact()
    .format(1234567);
  
// "9.8K"
final String likes = NumberFormat
    .compact()
    .format(9800);

compactLong spells the word out instead:

// "1.23 million"
final String views = NumberFormat
    .compactLong()
    .format(1234567);

NumberFormat does much more: sign control, money short forms like $1.2M, your own custom patterns, digit limits, rounding, and so on. For all of that, check the docs, or let your AI agent pick the best one.

The rule is: if the user reads it as "how much", format. If they read it as "which one", skip.

And here's an extension on num that covers 99% of the time:

extension NumX on num {
  String humanizedCount({
    int? decimalDigits,
  }) {
    return NumberFormat.decimalPatternDigits(
      decimalDigits: decimalDigits,
    ).format(this);
  }
  
  String humanizedCurrency(String code) {
    return NumberFormat.simpleCurrency(
      name: code,
    ).format(this);
  }
  
  String humanizedCompact() {
    return NumberFormat.compact().format(this);
  }
}