【问题标题】:Setting custom format for numbers in TextView [duplicate]在 TextView 中设置数字的自定义格式 [重复]
【发布时间】:2012-09-28 18:43:04
【问题描述】:

可能重复:
How do I format a number in java?
String.format() to format double in java

我希望能够从 double 变量(称为 double)中获取输出,并将其与一些字符串文本(称为 outputPref,仅包含“cubic mm”)一起放入 TextView 中,如下所示

displayAnswer.setText(volume + " " + outputPref);

这很好用,但是,文本视图中的数字显示为完整的双精度数(有很多小数位)。我希望用逗号将数以千计(如果有的话)显示为小数点后一位,例如 Excel 数字格式 "(* #,##0.0);(* ( #,##0.0);(* "-"??);(@_)",或者简单地说(假设我不会有任何负数) "#,##0.0"

在将音量加倍变量应用到 TextView 之前,我应该使用什么函数来重新配置它?

【问题讨论】:

    标签: java android format comma settext


    【解决方案1】:
    String.format("%1$,.2f", myDouble);
    

    【讨论】:

      【解决方案2】:

      使用这个

      NumberFormat format = NumberFormat.getInstance();
              format.setMaximumFractionDigits(1);
      displayAnswer.setText(format.format(volume)+ " "+outputPref);
      

      【讨论】:

        【解决方案3】:

        您可以将双数四舍五入以在 TextView 中显示:

        double roundTwoDecimals(double d) {
                    DecimalFormat twoDForm = new DecimalFormat("#.##");
                return Double.valueOf(twoDForm.format(d));
        }
        

        【讨论】:

        • 太棒了。如果我想用逗号分隔数千个 -> 即不是 roundTwoDecimals() 将 789455.566 转换为 789455.57 而是将其转换为 789,455.57?
        【解决方案4】:

        您可以设置小数位:

        DecimalFormat df = new DecimalFormat("#.#");
        

        这将在整数后给出一位小数,因为小数位后有一个#符号。

        然后做:

        df.format(yourDoubleHere);
        

        【讨论】:

          【解决方案5】:

          希望对你有帮助

          rountdoubel=Maths.round(outputPref)
          
          displayAnswer.setText(volume + " " + rountdoubel);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-02-29
            • 2013-08-23
            • 1970-01-01
            • 1970-01-01
            • 2016-08-18
            相关资源
            最近更新 更多