Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you set precision in darts?

In Dart, If you have a double and you need to set a certain precision to the number while rounding the value at the same time, you can use the following method. String toStringAsFixed(int fractionDigits); The method has one parameter fractionDigits which is used to set how many decimal points in the output.


See the docs for num.toStringAsFixed().

String toStringAsFixed(int fractionDigits)

Returns a decimal-point string-representation of this.

Converts this to a double before computing the string representation.

  • If the absolute value of this is greater or equal to 10^21 then this methods returns an exponential representation computed by this.toStringAsExponential().

Examples:

1000000000000000000000.toStringAsExponential(3); // 1.000e+21
  • Otherwise the result is the closest string representation with exactly fractionDigits digits after the decimal point. If fractionDigits equals 0 then the decimal point is omitted.

The parameter fractionDigits must be an integer satisfying: 0 <= fractionDigits <= 20.

Examples:

1.toStringAsFixed(3);  // 1.000
(4321.12345678).toStringAsFixed(3);  // 4321.123
(4321.12345678).toStringAsFixed(5);  // 4321.12346
123456789012345678901.toStringAsFixed(3);  // 123456789012345683968.000
1000000000000000000000.toStringAsFixed(3); // 1e+21
5.25.toStringAsFixed(0); // 5

num.toStringAsFixed() rounds. This one turns you num (n) into a string with the number of decimals you want (2), and then parses it back to your num in one sweet line of code:

n = num.parse(n.toStringAsFixed(2));

Above solutions do not appropriately round numbers. I use:

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

var price = 99.012334554;
price = price.toStringAsFixed(2);
print(price); // 99.01

That is the ref of dart. ref: https://api.dartlang.org/stable/2.3.0/dart-core/num/toStringAsFixed.html


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
}

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

Prints: 1.23


I used the toStringAsFixed() method, to round a number to specific numbers after the decimal point EX:

double num = 22.48132906

and when I rounded it to two numbers like this:

print(num.toStringAsFixed(2)) ;

It printed 22.48

and when I rounded to one number, it printed 22.5