Search code examples
flutterdartdouble

Round off to nearest hundred in dart


I came to a part in my flutter app where I need to round up to the nearest hundred and thought that there was probably some way to do it but I guess not. So I searched the net for examples or any answers and I've yet to find any since all examples appear to be to the nearest hundred. I just want to do this and round UP. Maybe there's some simple solution that I'm overlooking. I have tried double.roundToDouble() but it does not work for me. If anyone could help me with this issue I would greatly appreciate it.

If my number is 199.03, I want the result rounded to 200.00.

199.08->200.00
99.30->100.00
14.99->15.00
499.09->500.00

What I tried

.roundToDouble (this does not work as 199.08.roundToDouble returns as 199.0)

Solution

  • Here is an example I wrote. You can try it by pasting it dartpad.dev

      List<double> examples = [
        199.08,
        99.3,
        14.99,
        499.09,
      ];
    
      for (int i = 0; i < examples.length; i++) {
        double num = examples[i];
    
        double roundedNumber = num.ceilToDouble();
    
        print("$num -> $roundedNumber");
      }
    

    You can use ceil method to achieve this.

    RESULT:

    199.08 -> 200
    99.3 -> 100
    14.99 -> 15
    499.09 -> 500