How to specify RoundingMode for decimal numbers in Jasper Reports

前端 未结 2 973
天命终不由人
天命终不由人 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 03:46

    You can use the scriptlets mechanism.

    The sample

    • Java class
    package utils;
    
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.text.DecimalFormat;
    
    public class RoundingHelper {
    
        public static String round(BigDecimal value, RoundingMode mode, String pattern) {
            DecimalFormat format = new DecimalFormat(pattern);
            format.setRoundingMode(mode);
            return format.format(value);
        }
    }
    
    • The report's template:
    
    
        
        
            
        
        
        
        
            
                
                    
                    
                        
                        
                        
                        
                    
                    
                        
                    
                    
                
                
                    
                    
                        
                        
                        
                        
                    
                    
                        
                    
                    
                
                
                    
                    
                        
                        
                        
                        
                    
                    
                        
                    
                    
                
            
        
        
            
                
                    
                    
                        
                        
                        
                        
                    
                    
                    
                
                
                    
                    
                        
                        
                        
                        
                    
                    
                    
                
                
                    
                    
                        
                        
                        
                        
                    
                    
                    
                
            
        
    
    
    • The result will be (preview in iReport)

    The report in iReport

    Another solution

    Another way is to use BigDecimal.setScale(int, java.math.RoundingMode) method (for double field):

     
    

    or just (for BigDecimal field):

     
        
    

    More info about the scriptlets in JR: Scriptlets

提交回复
热议问题