Dart - NumberFormat

你说的曾经没有我的故事 提交于 2019-12-22 04:05:30

问题


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.


回答1:


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



回答2:


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;
}



回答3:


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.




回答4:


Maybe you don't want use NumberFormat:

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


来源:https://stackoverflow.com/questions/39958472/dart-numberformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!