decimal to double flutter code example

Example 1: double 2 decimal places flutter

/// Define an extension:
extension Ex on double {
  double toPrecision(int n) => double.parse(toStringAsFixed(n));
}

/// Usage:
void main() {
  double d = 2.3456789;
  double d1 = d.toPrecision(1); // 2.3
  double d2 = d.toPrecision(2); // 2.35
  double d3 = d.toPrecision(3); // 2.345
}

Example 2: double to int flutter

double x = 2.5;
 
  int a = x.toInt();
  int b = x.truncate();
  int c = x.round();
  int d = x.ceil();
  int e = x.floor();
 
  print(a); // 2
  print(b); // 2
  print(c); // 3
  print(d); // 3
  print(3); // 2

Tags:

Dart Example