Dart - NumberFormat

后端 未结 7 1008
北荒
北荒 2021-02-19 00:08

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 yo

7条回答
  •  感情败类
    2021-02-19 00:41

    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
    

提交回复
热议问题