2.7 C
New York
Wednesday, November 29, 2023

How to round a number in Dart

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:

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

Advertisements

Related Articles

Latest Articles