我从j表中获取值。我希望显示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
答案 0 :(得分:2)
我认为你可以使用它:
double dcost = (double) tableSale.getValueAt(i-1, 2);
String text = new DecimalFormat("##.##").format(dcost);
与其余的双倍值相同。
希望这有帮助!
答案 1 :(得分:1)
double d;
System.out.printf(".2f",d);
答案 2 :(得分:0)
尝试
String.format("%.2f", 123.0)
//小数点后两位。
和
String.format("%.0f", 123.0)
//没有小数点。
输出:
123.00
123
答案 3 :(得分:0)
对于费用,我建议不要加倍。改为使用BigDecimal。
格式化:
String.format("%.2d", dcost);
和String.format("%.0d", qty);
可以使用。
答案 4 :(得分:0)
如果要舍入到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
。