format method

String format({
  1. required int position,
  2. bool isCrop = false,
})

取n位小数,不足补位 position 要保留的位数 isCrop true 直接裁剪 false 四舍五入

Implementation

String format({required int position, bool isCrop = false}) {
  String t = this.toString();
  if (position < 0) {
    return t;
  }
  if (t.contains(".")) {
    String t1 = t.split(".").last;
    if (t1.length >= position) {
      if (isCrop) {
        return t.substring(0, t.length - (t1.length - position));
      } else {
        return this?.toStringAsFixed(position) ?? "";
      }
    } else {
      String t2 = "";
      for (int i = 0; i < position - t1.length; i++) {
        t2 += "0";
      }
      return t + t2;
    }
  } else {
    String t3 = position > 0 ? "." : "";
    for (int i = 0; i < position; i++) {
      t3 += "0";
    }
    return t + t3;
  }
}