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

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

显示一个小数点后两位用逗号分隔的数字,如 1,000.12 使用

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

当我使用下面的,什么都没有显示。

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

最佳答案

您调用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);

关于java - 使用逗号分隔符将 double 转换为 2 位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26509467/

相关文章:

java - 使用java在schema下创建表

java - 数组实例化调用构造函数?

java - 启动 Quartz Scheduler 而不触发触发器

java - 获取 gCal :color from google api for java?

java - 如何将经纬度从 Leaflet CRS.Simple 转换为 EPSG :4326

redirect - 如何重新加载我的页面以重定向到 VAADIN 中的 URI 片段?

java - 如何在 vaadin 中格式化表值?

java - Android AsyncHttpClient post() 进入 Fragment 中的无限循环

java - 如何在vaadin中设置图像数据源

maven - vaadin-maven-archetype - 为什么它会生成三个模块?