round function

num round(
  1. num x, [
  2. int decimalPlaces = 0
])

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

x is the number to be rounded. decimalPlaces specifies the number of decimal places to round to.

Implementation

num round(num x, [int decimalPlaces = 0]) {
  if (decimalPlaces == 0) {
    return x.round();
  } else {
    return (x * math.pow(10, decimalPlaces)).round() /
        math.pow(10, decimalPlaces);
  }
}