toText method

String toText([
  1. int fractionDigits = 2
])

If fractionDigits is 0, the value is formatted with no decimal places. Otherwise, it is formatted with the specified number of decimal places, and trailing zeros are removed.

Example:

String number = null.toText(2);
print(number); // Output:

number = 15.0005.toText(2);
print(number); // Output: 15

number = 15.0505.toText(2);
print(number); // Output: 15.05

Implementation

String toText([int fractionDigits = 2]) {
  if (this == null) return "";
  if (this is int) return toString();
  final value = this ?? 0.0;
  if (fractionDigits == 0) return value.toStringAsFixed(0);
  return "${value.toStringAsFixed(fractionDigits).replaceAll(RegExp(r"([.]*0+)(?!.*\d)"), "")}${fractionDigits > 1 ? " " : ""}";
}