给定一个double,我希望将它四舍五入到小数点后的给定精度点数,类似于PHP的round()函数。

我能在Dart文档中找到的最接近的东西是double.toStringAsPrecision(),但这不是我所需要的,因为它包括了精度总分中小数点前的数字。

例如,使用toStringAsPrecision(3):

0.123456789 rounds to 0.123  
9.123456789 rounds to 9.12  
98.123456789 rounds to 98.1  
987.123456789 rounds to 987  
9876.123456789 rounds to 9.88e+3

随着数字大小的增加,小数点后的精度也相应降低。


当前回答

从来没有想过这在Dart是如此复杂,但这是我的解决方案:

double truncateDouble(double val, int decimals) {
    String valString = val.toString();
    int dotIndex = valString.indexOf('.');

    // not enough decimals
    int totalDecimals = valString.length - dotIndex - 1;
    if (totalDecimals < decimals) {
      decimals = totalDecimals;
    }

    valString = valString.substring(0, dotIndex + decimals + 1);

    return double.parse(valString);
  }

var val = truncateDouble(44.999, 2);

其他回答

我使用toStringAsFixed()方法将一个数字四舍五入到小数点后的特定数字 例:

double num = 22.48132906

当我四舍五入到像这样的两个数字时:

print(num.toStringAsFixed(2)) ;

结果是22.48

当我四舍五入到一个数字时,它显示出22.5

要将Dart中的double整入到小数点后的给定精度,可以使用Dart toStringAsFixed()方法中的内置解决方案,但必须将其转换回double

void main() {
  double step1 = 1/3;  
  print(step1); // 0.3333333333333333
  
  String step2 = step1.toStringAsFixed(2); 
  print(step2); // 0.33 
  
  double step3 = double.parse(step2);
  print(step3); // 0.33
}

您可以简单地将该值乘以100,然后四舍五入,然后再除以100。

(number * 100).round() / 100.0;
void main() {
  int decimals = 2;
  int fac = pow(10, decimals);
  double d = 1.234567889;
  d = (d * fac).round() / fac;
  print("d: $d");
}

打印: 1.23

如果你需要适当的四舍五入(当第一位数字是5时向上),并且你想要后面有0,你可以使用这个方法:

import 'dart:math';

String customRound(double val, int places) {
  num mod = pow(10.0, places);
  return ((val * mod).round().toDouble() / mod).toStringAsFixed(places);
}

customRound(2.345) // -> 2.35
customRound(2.500) // -> 2.50