round function

int? round(
  1. dynamic value
)

Rounds value to the nearest integer.

  • Accepts int, double, or numeric String.
  • If value is already an int, it is returned unchanged.
  • If value is a double, returns the result of .round().
  • If value is a String, attempts to parse it as a double and then rounds the result.
  • Returns null if value is null.
  • Throws Exception if value is not a supported type.

Example:

round(3.6);       // -> 4
round("7.2");     // -> 7
round(5);         // -> 5
round(null);      // -> null

Implementation

int? round(dynamic value) {
  if (value == null) return null;
  if (value is int) return value;
  if (value is double) return value.round();
  if (value is String) return double.parse(value).round();
  throw Exception("Invalid value '$value' for 'round' function.");
}