Java: Use DecimalFormat to format doubles and integers but keep integers without a decimal separator

前端 未结 2 922
孤城傲影
孤城傲影 2020-12-17 10:23

I\'m trying to format some numbers in a Java program. The numbers will be both doubles and integers. When handling doubles, I want to keep only two decimal points but when h

2条回答
  •  感动是毒
    2020-12-17 11:13

    You can just set the minimumFractionDigits to 0. Like this:

    public class Test {
    
        public static void main(String[] args) {
            System.out.println(format(14.0184849945)); // prints '14.01'
            System.out.println(format(13)); // prints '13'
            System.out.println(format(3.5)); // prints '3.5'
            System.out.println(format(3.138136)); // prints '3.13'
        }
    
        public static String format(Number n) {
            NumberFormat format = DecimalFormat.getInstance();
            format.setRoundingMode(RoundingMode.FLOOR);
            format.setMinimumFractionDigits(0);
            format.setMaximumFractionDigits(2);
            return format.format(n);
        }
    
    }
    

提交回复
热议问题