To round a double number to two decimal places in Dart and Flutter, you can use the toStringAsFixed() method.
Note: You can set an arbitrary number of decimal places, like this: toStringAsFixed(N). However, numbers are usually displayed with 2 decimal places in most cases.
Example
The code:
import 'package:flutter/foundation.dart';
void main() {
const number1 = 1.233;
const number2 = 4.357;
const number3 = 10.994;
if (kDebugMode) {
print(number1.toStringAsFixed(2));
print(number2.toStringAsFixed(2));
print(number3.toStringAsFixed(2));
}
}
Output:
1.23
4.36
10.99
Further reading:
- Dart: Convert Class Instances (Objects) to Maps and Vice Versa
- How to Flatten a Nested List in Dart
- Inheritance in Dart: A Quick Example
- Flutter & Dart: 3 Ways to Generate Random Strings
- Flutter & Dart: Displaying Large Numbers with Digit Grouping
- Using Cascade Notation in Dart and Flutter
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.