【问题标题】:How to remove trailing zeros using Dart如何使用 Dart 删除尾随零
【发布时间】:2019-08-04 17:41:40
【问题描述】:

我想要使用 Dart 删除尾随零的最佳解决方案。如果我有一个 12.0 的双精度,它应该输出 12。如果我有一个 12.5 的双精度,它应该输出 12.5

【问题讨论】:

    标签: dart flutter


    【解决方案1】:
    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');
      }
    

    尝试修剪方法https://api.dartlang.org/stable/2.2.0/dart-core/String/trim.html

    【讨论】:

      【解决方案2】:

      更新
      更好的方法,就用这个方法:

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


      这符合要求:

      双倍 x = 12.0;
      双 y = 12.5;

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

      X 输出:12
      Y 输出:12.5

      【讨论】:

      • 如果变量 x/y 不是双精度则不起作用。
      • 它不适用于 99.96,它给了我 100。
      【解决方案3】:

      我为该功能制作了正则表达式模式。

      double num = 12.50; // 12.5
      double num2 = 12.0; // 12
      double num3 = 1000; // 1000
      
      RegExp regex = RegExp(r'([.]*0)(?!.*\d)');
      
      String s = num.toString().replaceAll(regex, '');
      

      【讨论】:

      • 这适用于所有场景。我的答案中的 toStringAsFixed(n.truncateToDouble() 方法会在小于 1(即 0.95)时将基于小数位的值自动舍入为 1,这是一种不需要的副作用。
      • 你为什么不使用你已经声明和分配的正则表达式?就是这部分:RegExp regex = RegExp(r"([.]*0)(?!.*\d)"); 相反,你给replaceAll 提供了一个新的正则表达式。
      • double numx = 12.500; 返回值为12.50;
      • RegExp(r'\.0') 对我来说更好
      • @alexwan02 使用RegExp(r"([.]*0+)(?!.*\d)") 删除小数点后的所有尾随零。
      【解决方案4】:

      我想出了改进版的@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
      

      【讨论】:

      • 这是不正确的。当您超过 100 时,您将获得 10。
      【解决方案5】:

      使用数字格式:

      String formatQuantity(double v) {
        if (v == null) return '';
      
        NumberFormat formatter = NumberFormat();
        formatter.minimumFractionDigits = 0;
        formatter.maximumFractionDigits = 2;
        return formatter.format(v);
      }
      

      【讨论】:

        【解决方案6】:

        如果您想要将没有小数的双精度数转换为整数,但如果它有小数,则将其保留为双精度数,我使用此方法:

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

        【讨论】:

        • 太棒了!干杯西蒙C
        【解决方案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;
        }
        

        ======= 下面的测试用例 =======

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

        【讨论】:

          【解决方案8】:

          这是一个非常简单的方法。使用 if else 我将检查数字是否等于整数或分数并采取相应措施

          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();
          }
          

          【讨论】:

            【解决方案9】:

            我找到了另一种解决方案,使用 num 而不是 double。在我的情况下,我将 String 解析为 num:

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

            【讨论】:

              【解决方案10】:

              为了改进 @John 的回答:这是一个较短的版本。

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

              【讨论】:

                【解决方案11】:

                user3044484 的 Dart 扩展版本:

                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);
                  }
                }
                

                【讨论】:

                • 最后一行应该是return trimmed.substring(0, trimmed.length - 1);
                【解决方案12】:

                这是我想出的:

                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);
                      });
                    });
                  });
                }
                

                【讨论】:

                • 很好的答案,即使有多个尾随零,它也可以工作。谢谢。
                【解决方案13】:
                // 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
                

                【讨论】:

                  【解决方案14】:

                  许多答案不适用于小数点多且以货币价值为中心的数字。

                  无论长度如何,删除所有尾随零:

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

                  输入:12.00100003000

                  输出:12.00100003

                  如果您只想删除小数点后的尾随 0,请改用:

                  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
                        );
                      }
                    }
                  

                  【讨论】:

                    猜你喜欢
                    • 2011-05-30
                    • 2012-01-26
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-07-08
                    • 2011-10-27
                    • 2018-09-28
                    • 2019-02-03
                    • 2022-01-07
                    相关资源
                    最近更新 更多