Dart - NumberFormat

Not very easily. Interpreting what you want as printing zero decimal places if it's an integer value and precisely two if it's a float, you could do

var forInts = new NumberFormat();
var forFractions = new NumberFormat();

forFractions.minimumFractionDigits = 2;
forFractions.maximumFractionDigits = 2;

format(num n) => 
    n == n.truncate() ? forInts.format(n) : forFractions.format(n);

print(format(15.50));
print(format(15.0));

But there's little advantage in using NumberFormat for this unless you want the result to print differently for different locales.


Edit: The solution posted by Martin seens to be a better one

I don't think this can be done directly. You'll most likely need something like this:

final f = new NumberFormat("###.00");

String format(num n) {
  final s = f.format(n);
  return s.endsWith('00') ? s.substring(0, s.length - 3) : s;
}

Actually, I think it's easier to go with truncateToDouble() and toStringAsFixed() and not use NumberFormat at all:

n.toStringAsFixed(n.truncateToDouble() == n ? 0 : 2);

So for example:

main() {
  double n1 = 15.00;
  double n2 = 15.50;

  print(format(n1));
  print(format(n2));
}

String format(double n) {
  return n.toStringAsFixed(n.truncateToDouble() == n ? 0 : 2);
}

Prints to console:

15
15.50

Maybe you don't want use NumberFormat:

class DoubleToString {
  String format(double toFormat) {
    return (toFormat * 10) % 10 != 0 ?
      '$toFormat' :
      '${toFormat.toInt()}';
  }
}