16

How can a number be rounded up to the nearest whole number in Flutter?

  • 0.1 => 1
  • 1.5 => 2
  • -0.1 => -1

The Num round methods rounds to the nearest integer. How can one always round up?

Ray Li
  • 7,601
  • 6
  • 25
  • 41
  • 1
    `-0.1 => -1` is not "rounding up". "Rounding up" means "toward positive infinity". What you're asking for is to round away from zero. – jamesdlin Jul 18 '20 at 20:15

2 Answers2

30

You can use the .ceil() method to achieve what you want.

Example:

print(-0.1.ceil()); => -1
print(1.5.ceil()); => 2
print(0.1.ceil()); => 1
void
  • 12,787
  • 3
  • 28
  • 42
  • This answer is incorrect as well. `double number = -0.1; number.ceil() => 0`. While `-0.1.ceil()` rounds to `-1`, the `ceil` method seems to round the number first and then applies the sign. This is likely why `ceil` is incorrect if the number is variable which encompasses the sign. – Ray Li Jul 18 '20 at 19:40
7

To round up to the nearest whole number in an absolute sense, use ceil if the number is positive and floor if the number is smaller than 0.

The following function rounds numbers up to the closest integer.

static int roundUpAbsolute(double number) {
  return number.isNegative ? number.floor() : number.ceil();
}

Or, use an extension function (6.3.roundUpAbs).

extension Round on double {
  int get roundUpAbs => this.isNegative ? this.floor() : this.ceil();
}
Ray Li
  • 7,601
  • 6
  • 25
  • 41
  • 1
    This answer rounds all doubles correctly. `-0.1` is rounded to `-1`. Your answer does not round double variables correctly. – Ray Li Jul 18 '20 at 19:42