Home > Net >  How to format nulls in DecimalFormat
How to format nulls in DecimalFormat

Time:12-18

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.

CodePudding user response:

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