How to specify RoundingMode for decimal numbers in Jasper Reports

前端 未结 2 974
天命终不由人
天命终不由人 2020-12-07 03:41

I\'m using Java with Jasper Reports and would like to format a decimal value using this format mask \"#,##0.00\". At the first sight all looks fine, but I found

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 04:08

    Here is another solution.

    You can change the default rounding mode of the number formatter by extending the default JR format factory (net.sf.jasperreports.engine.util.DefaultFormatFactory) and sending an instance of the extended factory via the JRParameter.REPORT_FORMAT_FACTORY parameter.

    The rounding mode of a java.text.DecimalFormat instance can be changed via the setRoundingMode() method.

    https://community.jaspersoft.com/questions/528989/decimal-formatting-rounding-mode-problem

    I've created inner class:

        getParameters().put(REPORT_FORMAT_FACTORY, new DefaultFormatFactory() {
    
            @Override
            public NumberFormat createNumberFormat(String pattern, Locale locale) {
                NumberFormat format = null;
                if (pattern != null && pattern.trim().length() > 0) {
                    if (STANDARD_NUMBER_FORMAT_DURATION.equals(pattern)) {
                        format = new DurationNumberFormat();
                    } else {
                        format = locale == null ?
                                NumberFormat.getNumberInstance() :
                                NumberFormat.getNumberInstance(locale);
                        if (format instanceof DecimalFormat) {
                            format.setRoundingMode(HALF_UP);
                            ((DecimalFormat) format).applyPattern(pattern);
                        }
                    }
                }
                return format;
            }
        });`
    

提交回复
热议问题