format static method
Formats value with up to decimals fractional digits, trimming trailing
zeros. Handles NaN / infinity gracefully.
Implementation
static String format(double value, {int decimals = 1}) {
if (value.isNaN) return 'NaN';
if (value.isInfinite) return value > 0 ? '∞' : '-∞';
final negative = value < 0;
final magnitude = value.abs();
var scale = 1;
for (var i = 0; i < math.max(0, decimals); i++) {
scale *= 10;
}
final scaled = (magnitude * scale).roundToDouble();
final whole = scaled ~/ scale;
final fracInt = (scaled.toInt()) % scale;
if (fracInt == 0 || decimals <= 0) {
return '${negative && (whole != 0 || scaled != 0) ? '-' : ''}$whole';
}
// Build the fractional part, trimming trailing zeros.
var digits = '$fracInt';
while (digits.length < decimals) {
digits = '0$digits';
}
while (digits.endsWith('0')) {
digits = digits.substring(0, digits.length - 1);
}
if (digits.isEmpty) {
return '${negative ? '-' : ''}$whole';
}
return '${negative ? '-' : ''}$whole.$digits';
}