regexflutterparsingdouble

How to know which numbers after . are non trailing zeros


I have, for example, 123.54054000. I want a function that returns 5, which is the number of decimals that I shouldn't ignore. I want to remove trailing zeros in my app.

Examples:

For 1.010 returns 2

for 1.7000 returns 1

for 1.123405607000 returns 9.


Solution

  • Convert the number to a string and use this function; it will return the number you want:

    int countSignificantDecimals(String number) {
      String trimmed = number.replaceFirst(RegExp(r'0+$'), '');
      
      int decimalIndex = trimmed.indexOf('.');
      if (decimalIndex == -1) {
        return 0;
      }
      return trimmed.length - decimalIndex - 1;
    }