String Formatting in Dart

Dart offers excellent support for string formatting. Here are some examples of common string formatting tasks.

import 'dart:io';

class Point {
  int x, y;
  Point(this.x, this.y);
}

void main() {
  // Dart offers several printing methods designed to
  // format general Dart values. For example, this prints
  // an instance of our `Point` class.
  var p = Point(1, 2);
  print('struct1: $p');

  // If the value is a class, the `toString()` method will be called.
  // You can override this method to include the class's field names.
  print('struct2: ${p.toString()}');

  // To print the type of a value, use `runtimeType`.
  print('type: ${p.runtimeType}');

  // Formatting booleans is straightforward.
  print('bool: ${true}');

  // There are many options for formatting integers.
  // Use `toString()` for standard, base-10 formatting.
  print('int: ${123}');

  // This prints a binary representation.
  print('bin: ${14.toRadixString(2)}');

  // This prints the character corresponding to the given integer.
  print('char: ${String.fromCharCode(33)}');

  // `toRadixString(16)` provides hex encoding.
  print('hex: ${456.toRadixString(16)}');

  // There are also several formatting options for floats.
  // For basic decimal formatting use `toStringAsFixed()`.
  print('float1: ${78.9.toStringAsFixed(6)}');

  // `toStringAsExponential()` formats the float in scientific notation.
  print('float2: ${123400000.0.toStringAsExponential()}');

  // For basic string printing, string interpolation is used.
  print('str1: ${"\"string\""}');

  // To double-quote strings, you can use raw string literals.
  print('str2: ${r'"string"'}');

  // As with integers seen earlier, `codeUnits` can be used to get
  // the UTF-16 code units of a string.
  print('str3: ${'hex this'.codeUnits.map((e) => e.toRadixString(16)).join()}');

  // To print a representation of an object's identity, use `identityHashCode`.
  print('pointer: ${identityHashCode(p)}');

  // When formatting numbers you will often want to control the width
  // and precision of the resulting figure. In Dart, you can use the
  // `padLeft()` method for this purpose.
  print('width1: |${12.toString().padLeft(6)}|${345.toString().padLeft(6)}|');

  // For floats, you can combine `toStringAsFixed()` with `padLeft()`.
  print('width2: |${1.2.toStringAsFixed(2).padLeft(6)}|${3.45.toStringAsFixed(2).padLeft(6)}|');

  // To left-justify, you can use `padRight()` instead.
  print('width3: |${1.2.toStringAsFixed(2).padRight(6)}|${3.45.toStringAsFixed(2).padRight(6)}|');

  // You may also want to control width when formatting strings.
  print('width4: |${'foo'.padLeft(6)}|${'b'.padLeft(6)}|');

  // To left-justify strings, use `padRight()`.
  print('width5: |${'foo'.padRight(6)}|${'b'.padRight(6)}|');

  // So far we've seen `print`, which prints the formatted string to stdout.
  // You can use string interpolation to format and return a string without printing it.
  var s = 'sprintf: a ${'string'}';
  print(s);

  // You can write to `stderr` using `stderr.writeln()`.
  stderr.writeln('io: an error');
}

To run the program, save it as string_formatting.dart and use dart run.

$ dart run string_formatting.dart
struct1: Instance of 'Point'
struct2: Instance of 'Point'
type: Point
bool: true
int: 123
bin: 1110
char: !
hex: 1c8
float1: 78.900000
float2: 1.234e+8
str1: "string"
str2: "string"
str3: 6865782074686973
pointer: 871939305
width1: |    12|   345|
width2: |  1.20|  3.45|
width3: |1.20  |3.45  |
width4: |   foo|     b|
width5: |foo   |b     |
sprintf: a string
io: an error

Now that we can format strings in Dart, let’s learn more about the language.