【问题标题】:java String formatting up to two decimal places with a char [duplicate]java使用char格式化最多两位小数的字符串[重复]
【发布时间】:2015-02-12 12:09:52
【问题描述】:

所以我在格式化字符串时遇到了问题。

我的输出应该总是##.##C or F(温度转换)

这是我的方法:

public void setResultLabel(double inNumber, char inChar)
{   

    String number, letter;

    number = String.valueOf(inNumber);

    letter = String.valueOf(inChar);

    String temp;

    temp = number + letter;

    String format = String.format("%2.5s", temp); /* how do you make this code 
    so that the out put result will always be up to two decimal places 
    with a char C or F? */

    result.setText(format);

    add(result);
}

【问题讨论】:

标签: java string format


【解决方案1】:

使用DecimalFormat 格式化十进制数。要将小数点从“,”更改为“。” (如果需要),使用DecimalFormatSymbols

public void setResultLabel(double inNumber, char inChar) {   
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator('.');
    DecimalFormat df = new DecimalFormat("##.##");
    df.setDecimalFormatSymbols(dfs);

    result.setText(df.format(inNumber) + inChar);
    add(result);
}

请注意,通常DecimalFormat 将是您类中的一个字段,因为您不想每次调用setResultLabel() 方法时都创建一个新的DecimalFormat 和一个新的DecimalFormatSymbols

【讨论】:

    【解决方案2】:

    您可以使用以下代码 sn-p 来实现所需的结果。

    double p =10.1234;
    char s = 'F';
    String formatted = String.format("%.2f%S", p, s);
    System.out.println(formatted);
    

    您可以在oracle 找到有关格式化的更多信息。请注意,还有其他替代方法可以实现输出,您可以找到有用的链接here

    【讨论】:

      【解决方案3】:
      public void setResultLabel(double inNumber, char inChar)
      {   
      
          String number, letter;
          DecimalFormat decimalFormat = new DecimalFormat("##.##"+inChar);
      
      
          String formated = decimalFormat.format(inNumber); 
          /* formated  is your result  */
          // System.out.println(formated);
      
          result.setText(format);
          add(result);
      }
      

      【讨论】:

      • 很高兴知道它有帮助。 @corkiiunranked
      猜你喜欢
      • 2016-09-28
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多