【问题标题】:How to hide decimal value when it is = 0如何隐藏十进制值 = 0
【发布时间】:2023-01-28 16:33:25
【问题描述】:

我目前正在尝试使用 Flutter 中的小部件呈现产品的价格价值。 为此,我传递状态并将其呈现在相应小部件的参数中。 我需要实现的是隐藏我的 Double 类型 priceValue 的 2 位小数,并在它们 != 为 0 时显示它们。

像这样,如果 state.priceValue = 12.00 $ => 应该显示 12 如果 state.priceValue = 12.30 $ => 应该显示 12.30

【问题讨论】:

    标签: flutter dart double


    【解决方案1】:
        String removeZero(double money) {
      var response = money.toString();
      var decmialPoint = money.toString().split(".")[1];
      if (decmialPoint == "0") {
        response = response.split(".0").join("");
      }
      if (decmialPoint == "00") {
        response = response.split(".00").join("");
      }
      return response;
    }
    

    有时小数点可能只有一个 0 所以我添加了第一个 if.. 其他一切都很简单

    【讨论】:

      【解决方案2】:

      尝试这个:

      String price = "12.00$"
      
      print(price.replaceAll(".00", ""));
      

      或者参考这个:How to remove trailing zeros using Dart

      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, '');
      

      但第二个选项将删除所有尾随零,因此 12.30 将改为 12.3

      【讨论】:

      • 感谢您的评论。不幸的是,这行不通,因为 price 是 Double,而不是 String。
      【解决方案3】:

      你好,你可以使用这样的扩展:

      extension myExtension on double{
       String get toStringV2{
        final intPart = truncate();
        if(this-intPart ==0){
         return '$intPart';
        }else{
         return '$this';
        }
       }
      }
      

      要使用扩展名:

      void main() {
       double numberWithDecimals = 10.8;
       double numberWithoutDecimals = 10.00;
       //print
       print(numberWithDecimals.toStringV2);
       print(numberWithoutDecimals.toStringV2);
      }
      

      【讨论】:

        猜你喜欢
        • 2020-02-05
        • 1970-01-01
        • 1970-01-01
        • 2020-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-15
        相关资源
        最近更新 更多