使用逗号分隔符将double转换为2位小数

时间:2014-10-22 14:08:53

标签: java vaadin7

在我看来,我有以下代码

IndexedContainer icLoaded = new IndexedContainer(); 
icLoaded.removeAllItems();  
icLoaded.removeAllContainerFilters();

icLoaded.addContainerProperty("Average Cost", Double.class, null);

在模型中,我有以下代码

public IndexedContainer DoFetchstockCodesTable(String passedSQL,
        IndexedContainer passTable, String CustomsaleQuerry) {

    try {

        Class.forName(dbsettings.dbDriver);

        final Connection conn = DriverManager.getConnection(
                new Home().GiveMeSessionDB(), dbsettings.dbUsername,
                dbsettings.dbPassword);
        final Statement stmt = conn.createStatement();

        ResultSet rs = stmt.executeQuery(passedSQL.trim());

        while (rs.next()) {

            passTable.addItem(rs.getString("item_id"));

            passTable.getContainerProperty(rs.getString("item_id"),
                    "Average Cost").setValue(rs.getDouble("average_cost"));

我如何转换下面的

 passTable.getContainerProperty(rs.getString("item_id"),
                    "Average Cost").setValue(rs.getDouble("average_cost"));

显示一个带有2位小数的数字,用逗号分隔符分隔,如使用

的1,000.12
 NumberFormat numberFormat = new DecimalFormat("#,###.00");

当我使用以下内容时,不会显示任何内容。

 passTable.getContainerProperty(rs.getString("item_id"),
                    "Average Cost").setValue(numberFormat.format(rs.getDouble("average_cost")));

2 个答案:

答案 0 :(得分:5)

您拨打NumberFormat#format(double)并将格式化的double保存为String,因为double是原始值且没有固有格式 -

NumberFormat numberFormat = new DecimalFormat("#,###.00");
double val = 1000.12;
System.out.println(numberFormat.format(val));

输出

1,000.12

修改

您需要更改此

icLoaded.addContainerProperty("Average Cost", Double.class, null);

icLoaded.addContainerProperty("Average Cost", String.class, null);

答案 1 :(得分:2)

您可以这样格式化值:

Table table = new Table() {
    @Override
    protected String formatPropertyValue(Object rowId, Object colId, Property<?> property) {
        if ("Average Cost".equals(colId)) {
            NumberFormat numberFormat = new DecimalFormat("#,###.00");
            return numberFormat.format(property.getValue());
        }
        return super.formatPropertyValue(rowId, colId, property);
    }
}