How do you double in Dart to a certain degree of accuracy AFTER the decimal point?

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

The closest thing I can find in Dart docs is double.toStringAsPrecision (), but that’s not exactly what I need, because it includes digits to the decimal point in common precision points.

For example, using 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 

As the value of the number increases, I accordingly lose accuracy after the decimal point.

+41
precision double-precision dart
source share
5 answers

See the docs for num.toStringAsFixed () .

String toStringAsFixed (int fractionDigits)

Returns a string representation of a decimal point.

Converts this value to double before evaluating the string representation.

If the absolute value of this value is greater than or equal to 10 ^ 21, then these methods return the exponential representation computed by this.toStringAsExponential (). Otherwise, the result will be the closest string representation with exactly fractional numbers of digits after the decimal point. If fractionDigits is 0, then the decimal point is omitted.

FractionDigits must be an integer that satisfies: 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 
+76
source share

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

 n = num.parse(n.toStringAsFixed(2)); 
+32
source share
 void main() { int decimals = 2; int fac = pow(10, decimals); double d = 1.234567889; d = (d * fac).round() / fac; print("d: $d"); } 

Print: 1.23

+11
source share

The above solutions do not round numbers. I use:

 double dp(double val, int places){ double mod = pow(10.0, places); return ((val * mod).round().toDouble() / mod); } 
+10
source share
  var price=99.012334554; price = price.toStringAsFixed(2); print(price); // 99.01 

This is a link to darts. link: https://api.dartlang.org/stable/2.3.0/dart-core/num/toStringAsFixed.html

+10
source share

All Articles