美文网首页
Flutter - 取n位小数

Flutter - 取n位小数

作者: hyq1101 | 来源:发表于2022-12-25 15:15 被阅读0次
     /**
       * target 要转换的数字
       * position 要保留的位数
       * isCrop true直接裁剪,false四舍五入
       */
      static String formartNum(num target, int postion, {bool isCrop = false}) {
        String t = target.toString();
        // 如果要保留的长度小于等于0,直接返回当前字符串
        if (postion < 0) {
          return t;
        }
        if (t.contains(".")) {
          String t1 = t.split(".").last;
          if (t1.length >= postion) {
            if (isCrop) {
              // 直接裁剪
              return t.substring(0, t.length - (t1.length - postion));
            } else {
              // 四舍五入
              return target.toStringAsFixed(postion);
            }
          } else {
            // 不够位数的补相应个数的0
            String t2 = "";
            for (int i = 0; i < postion - t1.length; i++) {
              t2 += "0";
            }
            return t + t2;
          }
        } else {
          // 不含小数部分补点和相应的0
          String t3 = postion > 0 ? "." : "";
          for (int i = 0; i < postion; i++) {
            t3 += "0";
          }
          return t + t3;
        }
      }
    

    相关文章

      网友评论

          本文标题:Flutter - 取n位小数

          本文链接:https://www.haomeiwen.com/subject/yfrgqdtx.html