Total Pageviews

2015/12/05

[Java] How to display double in 2 decimal places

Problem
I would like to pass a remarks report parameter to iReport. 
But the amount format should be formatted to 2 decimal places. ex1. 0 should display 0.00, ex2. 68.122223 should display 68.12

Original code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    public Report generateDbm030rReport(final String qryYear) {

        Map<String, BigDecimal> dataMap = createInitialMap();

        // query DB and merge
        dataMap = this.query(qryYear, dataMap);
  
  //....
  
        BigDecimal a1Amount = dataMap.get("A1");
        BigDecimal a8Amount = dataMap.get("A8");

        StringBuilder remarks = new StringBuilder();
        remarks.append("備註:<br />");
        remarks.append("1.本表統計各級政府向未納入集中支付基金及特定用途專戶調度周轉金額。<br />");
        remarks.append("2.截至 " + qryYear + " 年 12 月底止向各級政府納入集中支付支基金及特定用途專戶餘額如下:<br />");
        remarks.append("(1)中央政府: " + a1Amount + "  億元 <br />");
        remarks.append("(2)直轄市: " + a8Amount + "  億元 ");

        final String param[][] = { { "remark", remarks.toString() }, { "createOrg", org.getName() } };

        return this.generateReport("dbm030r1", param, dataMap);
    }


How-to
Updated code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 public Report generateDbm030rReport(final String qryYear) {

        Map<String, BigDecimal> dataMap = createInitialMap();

        // query DB and merge
        dataMap = this.query(qryYear, dataMap);
  
  //....
  
        BigDecimal a1Amount = dataMap.get("A1");
        BigDecimal a8Amount = dataMap.get("A8");

        StringBuilder remarks = new StringBuilder();
        remarks.append("備註:<br />");
        remarks.append("1.本表統計各級政府向未納入集中支付基金及特定用途專戶調度周轉金額。<br />");
        remarks.append("2.截至 " + qryYear + " 年 12 月底止向各級政府納入集中支付支基金及特定用途專戶餘額如下:<br />");
        remarks.append("(1)中央政府: " + customFormat(a1Amount) + "  億元 <br />");
        remarks.append("(2)直轄市: " + customFormat(a8Amount) + "  億元 ");

        final String param[][] = { { "remark", remarks.toString() }, { "createOrg", org.getName() } };

        return this.generateReport("dbm030r1", param, dataMap);
    }
 
     private String customFormat(BigDecimal amt) {
        return String.format("%.2f", amt.doubleValue());
    }


Reference
[1] http://stackoverflow.com/questions/5195837/format-float-to-n-decimal-places

No comments: