roundWithPrecision method
Number
roundWithPrecision(
- int precision, [
- RoundingMode mode = RoundingMode.nearestEven
override
Returns number rounded according to precision
and RoundingMode.
If precision
is negative, number is rounded to hundreds (-2), thousands (-3), etc. In that case, it rounds to nearest, ties away from zero.
If rounded number is integer, rounding mode nearestEven
is automatically used and cannot be changed.
Rounding modes: (https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules, https://upload.wikimedia.org/wikipedia/commons/8/8a/Comparison_rounding_graphs_SMIL.svg)
nearestEven
(0) - rounds to the nearest value; if the number falls midway, it is rounded to the nearest value with an even least significant digitnearestOdd
(1) - rounds to the nearest value; if the number falls midway, it is rounded to the nearest value with an odd least significant digitnearestFromZero
(2) - rounds to the nearest value; if the number falls midway, it is rounded to the value which is the farthest from zeronearestToZero
(3) - rounds to the nearest value; if the number falls midway, it is rounded to the value which is the closest to zeronearestDownward
(4) - rounds to the nearest value; if the number falls midway, it rounds downnearestUpward
(5) - rounds to the nearest value; if the number falls midway, it rounds downtowardsZero
(6) - directed rounding towards zerofromZero
(7) - directed rounding from zeroup
(8) - directed rounding towards positive infinitydown
(9) - directed rounding towards negative infinity
Implementation
@override
Number roundWithPrecision(int precision,
[RoundingMode mode = RoundingMode.nearestEven]) {
if (precision >= 0) {
return Integer(value);
} else {
var multiplier = pow(10, -precision) as int;
final adder = 5 * (multiplier ~/ 10) * ((value < 0) ? -1 : 1);
return Integer(((value + adder) ~/ multiplier) * multiplier);
}
}