This tutorial gives you examples of how to round double
to N decimal places precision in Dart.
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. If the given fractionDigits
is 0, the result will be without decimal point. It must be greater than or equal to 0, otherwise it will throw RangeError
.
The method has a limitation regarding to maximum value supported. If the value is greater than 10^21, it will return an exponential representation computed by toStringAsExponential()
Below are some examples along with the output for each line commented out at the end of the line.
print(10.123.toStringAsFixed(0)); // 10
print(10.1.toStringAsFixed(2)); // 10.10
print(10.123.toStringAsFixed(2)); // 10.12
print(10.125.toStringAsFixed(2)); // 10.13
print(10.129.toStringAsFixed(2)); // 10.13
print(10.135.toStringAsFixed(2)); // 10.13
print(10.1201.toStringAsFixed(3)); // 10.120
Currently, Dart only supports half up rounding mode which means other rounding modes such as half up, half even, ceiling, and floor are not supported.
At this moment, you can set the decimal precision only when formatting the value to String. If you parse the result to double again, the decimal precision may change.
That's how to round double with a certain decimal precision. You may also be interested to know about how to convert between double
and int
in Dart.