Skip to content

How to round a double with Flutter/Dart

Flutter, Dart, Flutter Tips1 min read

If you're in a situation where you want to round a double into an integer with Flutter it's pretty simple to do. A lot of other languages usually have some sort of Math library but you don't even need that with Dart.

If you want to multiply an integer by a double for example and you want the result in integer form, the following won't work:

1final int number = 100 * 0.3;

It won't work because the result of the equation is a double. To round the result into an integer(which naturally can't have decimal places) you just need to use the round method. Here's an example that won't cause analysis or compile errors:

1final int number = (100 * 0.3).round();

You can also round the number back into a double instead if you want to with roundToDouble:

1final double number = (100 * 0.3).roundToDouble();

It's probably worth mentioning that round will round away from zero, this is explained further in the source code:

2 * Returns the integer closest to `this`.
3 *
4 * Rounds away from zero when there is no closest integer:
5 * `(3.5).round() == 4` and `(-3.5).round() == -4`.
6 *
7 * If `this` is not finite (`NaN` or infinity), throws an [UnsupportedError].
8 */
9 int round();

And that's really all there is to it. This is another post in a series of short Flutter/Dart tips I have wrote. Last week I wrote about formatting DateTime objects into a readable format, you can check that post out here if you want to.