简体   繁体   中英

How to format nulls in DecimalFormat

I'm using DecimalFormat to percents with 2 decimal places:

DecimalFormat fmt = new DecimalFormat("0.00%");
System.out.println(fmt.format(1.14));   // 114.00%
System.out.println(fmt.format(0.1201)); // 12.01%
System.out.println(fmt.format(null));   // I would like to show "--"

How do I specify the format for nulls? I want two dashes.

You need to define a custom formatter, but as the method DecimalFormat.format is final, you can't inherit the class and override the method

DashDecimalFormat fmt = new DashDecimalFormat("0.00%");
System.out.println(fmt.format(1.14));   // 114.00%
System.out.println(fmt.format(0.1201)); // 12.01%
System.out.println(fmt.format(null));   // --
class DashDecimalFormat {
    private final DecimalFormat formatter;
    public DashDecimalFormat(String pattern) {
        formatter = new DecimalFormat(pattern);
    }
    public String format(Object obj) {
        return obj == null ? "--" : formatter.format(obj);
    }
}

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