有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中设置双精度值的小数点后2位

我从j表中得到值。我想在小数点后2位显示成本,不在小数点后2位显示数量

目前两种输出都有一个小数位(123.0)

如何解决这个问题

DecimalFormat df= new DecimalFormat("0.00");    

            int i = tableSale.getRowCount();        
            String id = (String) tableSale.getValueAt(i-1, 0);
            String name = (String) tableSale.getValueAt(i-1, 1);
            double dcost =  (double) tableSale.getValueAt(i-1, 2);
            double cst=Double.valueOf(df.format(dcost));//setting 2 decimal places
            String cost = String.valueOf(cst);//converting double to string

            double dqty = (double) tableSale.getValueAt(i-1, 3);
            DecimalFormat dd=new DecimalFormat("0");
            double qt = Double.valueOf(dd.format(dqty));
            String qty = String.valueOf(dqty);//converting double to string

            double ditemDiscount = (double) tableSale.getValueAt(i-1, 4);
            String itemDiscount = String.valueOf(ditemDiscount);//converting double to string

            double dgrossTotal = (double) tableSale.getValueAt(i-1, 5);
            double gTotal=Double.valueOf(df.format(dgrossTotal));//setting 2 decimal places
            String grossTotal = String.valueOf(gTotal);//converting double to string

共 (5) 个答案

  1. # 1 楼答案

    我想你可以用这个:

     double dcost =  (double) tableSale.getValueAt(i-1, 2);
     String text = new DecimalFormat("##.##").format(dcost);
    

    对于其余的两倍值

    希望这有帮助

  2. # 2 楼答案

    double d;
    System.out.printf(".2f",d);
    
  3. # 3 楼答案

    如果你想四舍五入到小数点后2位,你可以使用这个函数

    double dcost = round2(tableSale.getValueAt(i-1, 2));
    

    这避免了格式化字符串的开销,这样您就可以分析它

    private static final double WHOLE_NUMBER = 1L << 53;
    public static double round2(double d) {
        final double factor = 1e2;
        return d > WHOLE_NUMBER || d < -WHOLE_NUMBER ? d :
                (long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor;
    }
    

    你可以根据口味调整factor

  4. # 4 楼答案

    试试看

    两个小数点

    String.format("%.0f", 123.0)//没有小数点

    输出:

      123.00
      123
    
  5. # 5 楼答案

    至于费用,我建议不要加倍。使用BigDecimal

    至于格式:

    String.format("%.2d", dcost);String.format("%.0d", qty);可以使用