How do you round a double in Dart to a given degree of precision AFTER the decimal point?

前端 未结 12 1051
[愿得一人]
[愿得一人] 2020-12-08 03:46

Given a double, I want to round it to a given number of points of precision after the decimal point, similar to PHP\'s round() function.

The closest thing I

12条回答
  •  感情败类
    2020-12-08 04:13

    Define an extension:

    extension Ex on double {
      double toPrecision(int n) => double.parse(toStringAsFixed(n));
    }
    

    Usage:

    void main() {
      double d = 2.3456789;
      double d1 = d.toPrecision(1); // 2.3
      double d2 = d.toPrecision(2); // 2.35
      double d3 = d.toPrecision(3); // 2.345
    }
    

提交回复
热议问题