如何使用Dart删除尾随零

时间:2019-03-13 22:34:19

标签: dart flutter

我想要使用Dart消除尾随零的最佳解决方案。如果我的double是12.0,则应该输出12。如果我的double是12.5,则应该输出12.5

15 个答案:

答案 0 :(得分:2)

更新
更好的方法,只需使用以下方法:

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

OLD
符合要求:

双倍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

答案 1 :(得分:2)

如果您想要将不带小数的双精度型转换为int,但如果要带小数则将其保持为双精度型,我可以使用以下方法:

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

答案 2 :(得分:1)

编辑

要完成您的方法,我们也可以这样做(这样一来,双精度就不会丢失)

String stringMyDouble(double x){
  int i = x.truncate() ;

  if(x == i){
    return i.toString();
  }

  return x.toString();
}

void main() {
  double x = 12.0;

  print(stringMyDouble(x));
 }

以下仅适用于dart2js:(


如果您的目的是将数字显示为字符串,则double类的toString()方法会自动为double保留必要的精度。

例如:

void main() {
  double x = 12.3450;
  double y = 12.1 ;

  print(x.toString());

  y -= .1;
  print(y.toString());
 }

=>

12.345
12

有关修剪的说明:对不起,我没有足够的声誉来评论其他答案:( trim()不会从字符串中删除“ 0”,因为这0不被视为字符串中的尾随/空白字符。

答案 3 :(得分:1)

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

double num = 12.50;  //12.5
double num2 = 12.0; //12
double num3 = 1000; //1000

RegExp regex = RegExp(r"([.]*0)(?!.*\d)");

答案 4 :(得分:1)

这是一种非常简单的方法。如果不是,我将使用其他方式检查数字是否等于整数或分数,并采取相应措施

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

答案 5 :(得分:1)

// 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

答案 6 :(得分:0)

我想出了@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

答案 7 :(得分:0)

使用NumberFormat:

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

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

答案 8 :(得分:0)

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

答案 9 :(得分:0)

我找到了另一种解决方案,使用public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); boolean firstRun = sharedPref.getBoolean(getString(R.string.firstRun), true); ArrayList<String> arrayList; Gson gson = new Gson(); if (firstRun) //app was run for 1st time { System.out.println("First run"); // initialize array as You want arrayList = new ArrayList<>(); arrayList.add("Some string"); String arrayJSON = gson.toJson(arrayList); // add values to SharedPreferences editor.putString(getString(R.string.nameOfValue), arrayJSON); editor.putBoolean(getString(R.string.firstRun), false); // apply changes editor.apply(); } else // app wasn't run for 1st time { System.out.println("Not first run"); String arrayJSON = sharedPref.getString(getString(R.string.nameOfValue), getString(R.string.defaultValue)); arrayList = gson.fromJson(arrayJSON, new TypeToken<ArrayList<String>>() { }.getType()); } for (String s : arrayList) { System.out.println(s); } } } 代替num。就我而言,我正在将String解析为num:

double

答案 10 :(得分:0)

要改善@John的回答:这是一个简短的版本。

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

答案 11 :(得分:0)

user3044484的Dart扩展版本:

<mat-form-field appearance="fill">
    <mat-label>Select an option</mat-label>
    <mat-select>
        <mat-option *ngFor="let country of dataSource.filteredData">{{country.name}}</mat-option>
    </mat-select>
</mat-form-field>

...

<table>
...
</table>

答案 12 :(得分:0)

这是我想出的:

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 :(得分:0)

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

删除所有尾随零而不管长度:

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

答案 14 :(得分:-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