Skip to main content

prefer-number-format

added in: 1.6.0
⚙️🛠
Pro+

Warns when int, num or double values are formatted with toString instead of NumberFormat.format().

⚙️ Config

Set ignored-invocations (default is empty) to ignore toString calls inside a specific invocation (example).

analysis_options.yaml
dart_code_metrics:
rules:
- prefer-number-format:
ignored-invocations:
- print

Example

❌ Bad:

void main() {
const int intValue = 5;
const double doubleValue = 5;
const num numValue = 5;

final intString = intValue.toString(); // LINT: Prefer using 'NumberFormat()' to convert a number to a string value.
final doubleString = doubleValue.toString(); // LINT: Prefer using 'NumberFormat()' to convert a number to a string value.
final numString = numValue.toString(); // LINT: Prefer using 'NumberFormat()' to convert a number to a string value.

final intString2 = '$intValue $5'; // LINT: Prefer using 'NumberFormat()' to convert a number to a string value.
final doubleString2 = '$doubleValue $5.1'; // LINT: Prefer using 'NumberFormat()' to convert a number to a string value.
final numString2 = '$numValue'; // LINT: Prefer using 'NumberFormat()' to convert a number to a string value.
}

✅ Good:

void main() {
const int intValue = 5;
const double doubleValue = 5;
const num numValue = 5;

final intString = NumberFormat().format(intValue);
final doubleString = NumberFormat().format(doubleValue);
final numString = NumberFormat().format(numValue);
}

Example with "ignored-invocations"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-number-format:
ignored-invocations:
- print

✅ Good:

void main() {
const int intValue = 5;

print(intValue); // Correct, ignored
}