【问题标题】:How to round double to 2 decimal places and remove zeros if exits using Dart?如果使用 Dart,如何将双精度舍入到小数点后 2 位并删除零?
【发布时间】:2021-04-05 23:48:39
【问题描述】:

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

这是我想要做的:

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

编辑:

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

String getFormattedNumber( num ) {

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

}

【问题讨论】:

    标签: flutter dart rounding truncate


    【解决方案1】:

    根据十进制表示对浮点数进行舍入没有多大意义,因为许多小数(例如0.3can't be exactly represented by floating point numbers anyway。 (这是所有浮点数固有的,并不是 Dart 特有的。)

    但是,您可以尝试使您的号码的 string 表示更漂亮。 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
    

    另见How to remove trailing zeros using Dart

    【讨论】:

    • 这个比你提到的另一个工作正常
    【解决方案2】:

    这是您想要的示例代码。

    1. 乘以 10^(点后的数字计数)
      如果点后的数字计数为 2
      9.25843223423423 -> 925.843223423423

    2. 第一轮)的结果
      925.843223423423 -> 926

    3. 除以 10^(点后的数)
      926 -> 9.26

    
    import 'dart:math';
    
    void main() {
      double x = 0.99;
      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
      
      print(customRound(x, 2));
      print(customRound(y, 2));
      print(customRound(z, 2));
      
      for(var i = 0.01 ; i < 1 ; i += 0.01) {
        print(customRound(i, 2));
      }
    }
    
    dynamic customRound(number, place) {
      var valueForPlace = pow(10, place);
      return (number * valueForPlace).round() / valueForPlace;
    }
    
    

    【讨论】:

    • 这不适用于大多数浮点值。尝试以 0.01 到 0.99 的所有值递增 0.01。故障率超过90%。
    • @user207421 嗯...让我知道从 0.01 到 0.99 测试的更改代码有什么问题。
    • 问题在于您的打印精度受限。在我提到的情况下,浮点 values 有更多。这是不可避免的,因为 base-10 和 base-20 是不可通约的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多