简体   繁体   中英

Convert a double to 2 decimal places with comma separator

In my view i have the below code

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

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

In the model i have the below code

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"));

How can i convert the below

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

to display a number with 2 decimal places separated by a comma separator like 1,000.12 using

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

When i use the below , nothing gets displayed .

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

You call NumberFormat#format(double) and save the formatted double as a String , because a double is a primitive value and it has no inherent formatting -

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

Output is

1,000.12

Edit

You need to change this

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

to

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

You can format the value in this way:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM