matth3o matth3o - 1 month ago 20
Dart Question

Dart - NumberFormat

Is there a way with

NumberFormat
to display :


  • '15' if double value is 15.00

  • '15.50' if double value is 15.50



Thanks for your help.

Answer

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