dart-round-double-feature-image

Dart – How to round double number

In this tutorial, we’re gonna show you how to round double number in Dart. You will know the ways to:

  • round double to int
  • round double to integer double value
  • round double to N decimal places


Dart round double to int

Using round() method, we can get an integer closest to a double.

For example:

int num1 = (2.3).round();
// 2

int num2 = (2.5).round();
// 3

int num3 = (-2.3).round();
// -2

int num4 = (-2.5).round();
// -3

Dart round double to integer double value

We can get an integer double value closest to a double with roundToDouble() method.

Remember that if a double d is in the range -0.5 < d < 0.0, the result will be -0.0.

For example:

double num1 = (2.3).roundToDouble();
// 2.0

double num2 = (2.5).roundToDouble();
// 3.0

double num3 = (-2.3).roundToDouble();
// -2.0

double num4 = (-2.5).roundToDouble();
// -3.0

double num5 = (-0.2).roundToDouble();
// -0.0

double num6 = (0.2).roundToDouble();
// 0.0

Dart round double to N decimal places

We have 2 ways to round double to N decimal places in Dart:

– Use toStringAsFixed() to get closest string representation with exactly N digits after the decimal point, then parse the result to double.

double num1 = double.parse((12.3412).toStringAsFixed(2));
// 12.34

double num2 = double.parse((12.5668).toStringAsFixed(2));
// 12.57

double num3 = double.parse((-12.3412).toStringAsFixed(2));
// -12.34

double num4 = double.parse((-12.3456).toStringAsFixed(2));
// -12.35

– Multiply the number by 10^N (using pow() function), then round the result to integer and divide it by 10^N.

For example, we want to round double to 2 decimal places. Assume that the number is 12.3412:

  • Step 1: 12.3412 * 10^2 = 1234.12
  • Step 2: round 1234.12 to 1234
  • Step 3: 1234 / 10^2 = 12.34

We will need to write a roundDouble() function with the help of dart:math library.

import 'dart:math';

double roundDouble(double value, int places){ 
   double mod = pow(10.0, places); 
   return ((value * mod).round().toDouble() / mod); 
}

main() {
  double num1 = roundDouble(12.3412, 2);
  // 12.34

  double num2 = roundDouble(12.5668, 2);
  // 12.57

  double num3 = roundDouble(-12.3412, 2);
  // -12.34

  double num4 = roundDouble(-12.3456, 2);
  // -12.35
}

Conclusion

Today we’ve known ways to round double to int, integer double value and to N decimal places.
Here are some useful posts that you may like:
Parse a String into a number in Dart/Flutter
Dart/Flutter String Methods & Operators

Happy Learning! See you again.

Further Reading

Leave a Reply

Your email address will not be published. Required fields are marked *