[英]Setting 2 decimal places in double value in Java
我從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
我想你可以用這個:
double dcost = (double) tableSale.getValueAt(i-1, 2);
String text = new DecimalFormat("##.##").format(dcost);
與其余的雙倍值相同。
希望這有幫助!
double d;
System.out.printf(".2f",d);
嘗試
String.format("%.2f", 123.0)
//兩個小數點。
和
String.format("%.0f", 123.0)
//表示無小數點。
輸出:
123.00
123
對於費用,我建議不要加倍。 請改用BigDecimal。
至於格式:
String.format("%.2d", dcost);
和String.format("%.0d", qty);
可以使用。
如果要舍入到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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.