Dart - NumberFormat

后端 未结 7 1005
北荒
北荒 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
    
    0 讨论(0)
  • 2021-02-19 00:41

    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;
    }
    
    0 讨论(0)
  • 2021-02-19 00:44

    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.

    0 讨论(0)
  • 2021-02-19 00:48

    Maybe you don't want use NumberFormat:

    class DoubleToString {
      String format(double toFormat) {
        return (toFormat * 10) % 10 != 0 ?
          '$toFormat' :
          '${toFormat.toInt()}';
      }
    }
    
    0 讨论(0)
  • 2021-02-19 00:49

    An alternate solution, working on the string output of NumberFormat:

    final f = NumberFormat("###.00");
    print(f.format(15.01).replaceAll('.00', ''));
    print(f.format(15.00).replaceAll('.00', ''));
    
    0 讨论(0)
  • 2021-02-19 00:50

    This will work.

    main() {
      double n1 = 15.00;
      double n2 = 15.50; 
    
      print(_formatDecimal(n1));
      print(_formatDecimal(n2));
    }
    
    _formatDecimal(double value) {
      if (value % 1 == 0) return value.toStringAsFixed(0).toString();
      return value.toString();
    }
    

    Output:

    15
    15.5
    
    0 讨论(0)
提交回复
热议问题