formatDecimal method
Formats the string to a valid decimal number with custom rules.
decimalPlaces
defines the number of allowed decimal places.
If convertToFloat
is true, the result is returned as a float-like string.
Implementation
String formatDecimal({int decimalPlaces = 2, bool convertToFloat = false}) {
if (this!.isEmpty) return this!;
// Parse the input string to a double
double? value = double.tryParse(this!);
if (value == null) return this!; // Return the original string if not a number
// Remove `.00` if the value is a whole number
String formatted = value.toStringAsFixed(
value.truncateToDouble() == value ? 0 : decimalPlaces,
);
// Return as float-like string if required
if (convertToFloat) {
return value.toString();
}
return formatted;
}