'How to remove trailing zeros using Dart

I would like the optimal solution for removing trailing zeros using Dart. If I have a double that is 12.0 it should output 12. If I have a double that is 12.5 it should output 12.5



Solution 1:[1]

UPDATE
A better approach, just use this method:

String removeDecimalZeroFormat(double n) {
    return n.toStringAsFixed(n.truncateToDouble() == n ? 0 : 1);
}

OLD
This meets the requirements:

double x = 12.0;
double y = 12.5;

print(x.toString().replaceAll(RegExp(r'.0'), ''));
print(y.toString().replaceAll(RegExp(r'.0'), ''));

X Output: 12
Y Output: 12.5

Solution 2:[2]

Use NumberFormat:

String formatQuantity(double v) {
  if (v == null) return '';

  NumberFormat formatter = NumberFormat();
  formatter.minimumFractionDigits = 0;
  formatter.maximumFractionDigits = 2;
  return formatter.format(v);
}

Solution 3:[3]

If what you want is to convert a double without decimals to an int but keep it as a double if it has decimals, I use this method:

num doubleWithoutDecimalToInt(double val) {
  return val % 1 == 0 ? val.toInt() : val;
}

Solution 4:[4]

Lots of the answers don't work for numbers with many decimal points and are centered around monetary values.

To remove all trailing zeros regardless of length:

removeTrailingZeros(String n) {
  return n.replaceAll(RegExp(r"([.]*0+)(?!.*\d)"), "");
}

Input: 12.00100003000

Output: 12.00100003

If you only want to remove trailing 0's that come after a decimal point, use this instead:

removeTrailingZerosAndNumberfy(String n) {
    if(n.contains('.')){
      return double.parse(
        n.replaceAll(RegExp(r"([.]*0+)(?!.*\d)"), "") //remove all trailing 0's and extra decimals at end if any
      );
    }
    else{
      return double.parse(
        n
      );
    }
  }

Solution 5:[5]

I found another solution, to use num instead of double. In my case I'm parsing String to num:

void main() {
 print(num.parse('50.05').toString()); //prints 50.05
 print(num.parse('50.0').toString()); //prints 50
}

Solution 6:[6]

Here is what I've come up with:

extension DoubleExtensions on double {
  String toStringWithoutTrailingZeros() {
    if (this == null) return null;
    return truncateToDouble() == this ? toInt().toString() : toString();
  }
}


void main() {
  group('DoubleExtensions', () {
    test("toStringWithoutTrailingZeros's result matches the expected value for a given double",
        () async {
      // Arrange
      final _initialAndExpectedValueMap = <double, String>{
        0: '0',
        35: '35',
        -45: '-45',
        100.0: '100',
        0.19: '0.19',
        18.8: '18.8',
        0.20: '0.2',
        123.32432400: '123.324324',
        -23.400: '-23.4',
        null: null
      };

      _initialAndExpectedValueMap.forEach((key, value) {
        final initialValue = key;
        final expectedValue = value;

        // Act
        final actualValue = initialValue.toStringWithoutTrailingZeros();

        // Assert
        expect(actualValue, expectedValue);
      });
    });
  });
}

Solution 7:[7]

String removeTrailingZero(String string) {
  if (!string.contains('.')) {
    return string;
  }
  string = string.replaceAll(RegExp(r'0*$'), '');
  if (string.endsWith('.')) {
    string = string.substring(0, string.length - 1);
  }
  return string;
}

======= testcase below =======

000 -> 000
1230 -> 1230
123.00 -> 123
123.001 -> 123.001
123.00100 -> 123.001
abc000 -> abc000
abc000.0000 -> abc000
abc000.001 -> abc000.001

Solution 8:[8]

Here is a very simple way. Using if else I will check if the number equals its integer or it is a fraction and take action accordingly

num x = 24/2; // returns 12.0
num y = 25/2; // returns 12.5

if (x == x.truncate()) {
// it is true in this case so i will do something like
x = x.toInt();
}

Solution 9:[9]

To improve on What @John's answer: here is a shorter version.

String formatNumber(double n) {
 return n.toStringAsFixed(0) //removes all trailing numbers after the decimal. 
 }

Solution 10:[10]

// The syntax is same as toStringAsFixed but this one removes trailing zeros
// 1st toStringAsFixed() is executed to limit the digits to your liking
// 2nd toString() is executed to remove trailing zeros

extension Ex on double {
  String toStringAsFixedNoZero(int n) =>            
  double.parse(this.toStringAsFixed(n)).toString(); 
}

// It works in all scenarios. Usage

void main() {

  double length1 = 25.001; 
  double length2 = 25.5487000; 
  double length3 = 25.10000;
  double length4 = 25.0000;
  double length5 = 0.9;

  print('\nlength1= ' + length1.toStringAsFixedNoZero(3));
  print('\nlength2= ' + length2.toStringAsFixedNoZero(3));
  print('\nlenght3= ' + length3.toStringAsFixedNoZero(3));
  print('\nlenght4= ' + length4.toStringAsFixedNoZero(3));
  print('\nlenght5= ' + length5.toStringAsFixedNoZero(0)); 

}

// output:

// length1= 25.001
// length2= 25.549
// lenght3= 25.1
// lenght4= 25
// lenght5= 1

Solution 11:[11]

user3044484's version with Dart extension:

extension StringRegEx on String {
  String removeTrailingZero() {
    if (!this.contains('.')) {
      return this;
    }

    String trimmed = this.replaceAll(RegExp(r'0*$'), '');
    if (!trimmed.endsWith('.')) {
      return trimmed;
    }

    return trimmed.substring(0, this.length - 1);
  }
}

Solution 12:[12]

you can do a simple extension on the double class and add a function which in my case i called it neglectFractionZero()

in this extension function on double(which returns a string) i split the converted number to string and i check if the split part of the string is "0" , if so i return the first part only of the split and i neglect this zero

you can modify it according to your needs

extension DoubleExtension on double { String neglectFractionZero() {

    return toString().split(".").last == "0"? toString().split(".").first:toString();
  }
}

Solution 13:[13]

I've came up with improved version of @John.

static String getDisplayPrice(double price) {
    price = price.abs();
    final str = price.toStringAsFixed(price.truncateToDouble() == price ? 0 : 2);
    if (str == '0') return '0';
    if (str.endsWith('.0')) return str.substring(0, str.length - 2);
    if (str.endsWith('0')) return str.substring(0, str.length -1);
    return str;
  }

// 10 -> 10
// 10.0 -> 10
// 10.50 -> 10.5
// 10.05 -> 10.05
// 10.000000000005 -> 10

Solution 14:[14]

void main() {
  double x1 = 12.0;
  double x2 = 12.5;
  String s1 = x1.toString().trim();
  String s2 = x2.toString().trim();
  print('s1 is $s1 and s2 is $s2');
  }

try trim method https://api.dartlang.org/stable/2.2.0/dart-core/String/trim.html