How to round a number in Dart

Last updated on January 28, 2022 Hadrianus Loading... Post a comment

In order to round numbers in Dart, we can use the round() method. This method returns the closest integer to the input number. If cannot determine the closest integer (e.g. 0.5, -2.5, 3.5, etc), rounds away from zero.

Example:

import 'package:flutter/foundation.dart';

void main() {
  var x = 10.3333;
  if (kDebugMode) {
    print(x.round());
  }

  var y = -1.45;
  if (kDebugMode) {
    print(y.round());
  }

  var z = 4.55;
  if (kDebugMode) {
    print(z.round());
  }

  var t = 1.5;
  if (kDebugMode) {
    print(t.round());
  }
}

Output:

10
-1
5
2

You can find more information about the round() method in the official docs.

Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles