如何将双精度数四舍五入到小数点后两位并删除尾随零?

MO *_* Mu 2 truncate rounding dart flutter

我找不到一种方法将双精度舍入到小数点后两位并删除 Dart 中的尾随零。我找到了一种舍入方法,但如果我尝试截断尾随零,它就不起作用。

这是我正在尝试做的事情:

double x = 5.0;
double y = 9.25843223423423;
double z = 10.10;

print(x); //Expected output --> 5
print(y); //Expected output --> 9.26
print(z); //Expected output --> 10.1
Run Code Online (Sandbox Code Playgroud)

编辑:

我找到了解决上面前两个打印语句的方法。我想我应该为搜索它的人添加它。

String getFormattedNumber( num ) {

  var result;
  if(num % 1 == 0) {
    result = num.toInt();
  } else {
    result = num.toStringAsFixed(2);
  }
return result.toString();
Run Code Online (Sandbox Code Playgroud)

}

jam*_*lin 8

根据十进制表示对浮点数进行舍入没有多大意义,因为许多小数分数(例如0.3无论如何都无法用浮点数精确表示。(这是所有浮点数所固有的,并不是 Dart 所特有的。)

但是,您可以尝试使数字的字符串表示更漂亮。num.toStringAsFixed四舍五入到指定的小数位数。从那里,您可以使用正则表达式来删除尾随零:

String prettify(double d) =>
    // toStringAsFixed guarantees the specified number of fractional
    // digits, so the regular expression is simpler than it would need to
    // be for more general cases.
    d.toStringAsFixed(2).replaceFirst(RegExp(r'\.?0*$'), '');

double x = 5.0;
double y = 9.25843223423423;
double z = 10.10;

print(prettify(x)); // Prints: 5
print(prettify(y)); // Prints: 9.26
print(prettify(z)); // Prints: 10.1

print(prettify(0)); // Prints: 0
print(prettify(1)); // Prints: 1
print(prettify(200); // Prints: 200
Run Code Online (Sandbox Code Playgroud)

另请参阅如何使用 Dart 删除尾随零