【问题标题】:Round up to two decimals in eclipse android在eclipse android中四舍五入到小数点后两位
【发布时间】:2013-05-01 08:16:36
【问题描述】:

谁能帮我把这个舍入到小数点后两位而不是在android中显示所有小数点?

【问题讨论】:

  • 将其转换为String,然后将其拆分为两位小数,然后将其转换回Integer或double。

标签: android eclipse decimal


【解决方案1】:

使用下面的代码。这将为您返回一个只有 2 位小数的字符串。

// Continuing from the code you have on thee link ... 
double Udregning = aValue * EuroTilKroner;
DecimalFormat df = new DecimalFormat("#.00");
String s = df.format(Udregning);
result.setText(s);

希望这有助于其他请评论。

更新

正如@Oren 建议的那样,您可以按如下方式设置舍入模式:

df.setRoundingMode(RoundingMode.HALF_EVEN);

更多模式见link

【讨论】:

    【解决方案2】:

    你可以使用String.format("%.2f", value),你的double会自动四舍五入。

    【讨论】:

      【解决方案3】:
         public static String roundAndFormatDouble(double value,int scale) {
         try {
           BigDecimal bd = new BigDecimal(value);
           bd = bd.setScale(scale, RoundingMode.HALF_UP);
           String roundedValue  = bd.toString();
           return roundedValue;
          } catch (Exception e) {
          e.printStackTrace();
          }
          return ""+value;
      }
      

      此 API 可以处理舍入和格式化部分。

      请注意,如果您使用 bd,doubleValue(),在某些情况下您可能无法获得精确缩放的小数位数。例如:50.0。

      【讨论】:

        【解决方案4】:

        试试这个:

        //continuing from code
        Udregning = aValue * EuroTilKroner;
        String abc = String.format("%.2f", Udregning);
        result.setText(abc);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-02
          • 2012-05-09
          • 1970-01-01
          • 2017-03-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多