round function
Rounds the number x
to the specified number of decimalPlaces
.
If decimalPlaces
is not provided or is 0, the function rounds x
to the nearest whole number. Otherwise, it rounds x
to the desired
number of decimal places.
Example:
print(round(123.4567, 2)); // Output: 123.46
print(round(123.4567)); // Output: 123
print(round(Complex(3.7, 2.9))); // Output: Complex(4, 3)
x
is the number to be rounded.
decimalPlaces
specifies the number of decimal places to round to.
Implementation
dynamic round(dynamic x, [int decimalPlaces = 0]) {
if (x is num) {
if (decimalPlaces == 0) {
return x.round();
} else {
return (x * math.pow(10, decimalPlaces)).round() / math.pow(10, decimalPlaces);
}
} else if (x is Complex) {
return x.roundTo(decimals: decimalPlaces).simplify();
} else {
throw ArgumentError('Input should be either num or Complex');
}
}