toStringAsSmartRound method

String toStringAsSmartRound({
  1. int maxPrecision = 2,
})

Cuts to maxPrecision decimals and drops trailing zeros. 2.50 → "2.5", 3.0 → "3"

Implementation

String toStringAsSmartRound({int maxPrecision = 2}) {
  final String str = toString();
  if (!str.contains(".") || str.contains("e")) return str;
  final int periodIndex = str.indexOf(".");
  final String wholePart = str.substring(0, periodIndex);
  final String mantissa = str.substring(periodIndex + 1, min(str.length, periodIndex + 1 + maxPrecision)).replaceAll(RegExp(r"0+$"), "");
  return mantissa.isEmpty ? wholePart : "$wholePart.$mantissa";
}