【问题标题】:formatting Double class in a TextView [duplicate]在 TextView 中格式化 Double 类 [重复]
【发布时间】:2018-12-30 17:56:50
【问题描述】:

我创建了一个名为Box 的静态类,并在那里计算参数double AverageWeight。

然后,在我的MainActivity 中,我想在TextView 中打印结果,并且只显示小数点后两位。我该怎么做?

我已经在 Stack Overflow 上搜索了这个问题,但我没有找到任何关于格式化 Double 类的内容,而且我没有尝试过任何工作。

//Convert the output from double to String
String avgWeight = Double.toString(Box.getAverageWeight());

//Set the String output to TextView
tv_resAvgWeight.setText(avgWeight);

【问题讨论】:

    标签: java android class format string-formatting


    【解决方案1】:

    可以使用JavaDecimalFormat类,例如:

    DecimalFormat format = new DecimalFormat("#.##");
    double d = 1.234242424;
    System.out.println(format.format(d));
    

    您可以阅读课程的full documentation,了解所有可用选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 2010-09-26
      • 1970-01-01
      相关资源
      最近更新 更多