Search code examples
dartnumber-formatting

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.


Solution

  • 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