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
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
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
}
The modified answer of @andyw using Dart Extension methods:
extension Precision on double {
double toPrecision(int fractionDigits) {
double mod = pow(10, fractionDigits.toDouble());
return ((this * mod).round().toDouble() / mod);
}
}
Usage:
var latitude = 1.123456;
var latitudeWithFixedPrecision = latitude.toPrecision(3); // Outputs: 1.123
To round a double in Dart to a given degree of precision AFTER the decimal point, you can use built-in solution in dart toStringAsFixed()
method, but you have to convert it back to 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
}
You can use toStringAsFixed
in order to display the limited digits after decimal points. toStringAsFixed
returns a decimal-point string-representation. toStringAsFixed
accepts an argument called fraction Digits
which is how many digits after decimal we want to display. Here is how to use it.
double pi = 3.1415926;
const val = pi.toStringAsFixed(2); // 3.14
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.
Examples:
1000000000000000000000.toStringAsExponential(3); // 1.000e+21
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