Search code examples
flutternumber-formatting

Flutter float number rounding


I want to achieve the following in my code, and can't seem to find a proper solution: I need code that will always show 6 digits of a number, no matter being int greater than 999999 or floating point smaller than 0.

100000 -> 100000
1000000 -> 100000

10000.0 -> 10000
100.01111 -> 100.011

0.000001 -> 0
0.000011 -> 0.00001

With some help in the comments, I got a solution that works for me. If someone has more elegant way of doing this please do share it.

int desiredPrecision = 6;
int numberOfDigitsOnTheLeft = val.toInt().toString().length;
String sixDigitString = val.toStringAsFixed(desiredPrecision-numberOfDigitsOnTheLeft);

Solution

  • as an option

    void main() {
        print(_normalizeNum(10000.0));
        print(_normalizeNum(100000));
        print(_normalizeNum(1000000));
        print(_normalizeNum(10000.0));
        print(_normalizeNum(100.01111));
        print(_normalizeNum(0.000001));
        print(_normalizeNum(0.000011));
    }
    
    String _normalizeNum(num d) {
      d = d.clamp(double.negativeInfinity, 999999);
      d = num.parse(d.toStringAsFixed(6).substring(0, 7));
      if (d == d.toInt()) {
        d = d.toInt();
      }
      return d.toString();
    }