How to round a number in Dart

Updated: February 6, 2023 By: Hadrianus Post a comment

In order to round a float number to an integer 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

If you provide an input number that is not finite (NaN or an infinity), the round() method will throw an UnsupportedError exception.

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