Java: use decimalformat to format doubles and integers, but keep integers without decimal separator

I tried to format some numbers in a java program Numbers will be double and integer When dealing with double precision, I only want to keep two decimal points, but when dealing with integers, I want the program to remain unchanged To put it another way:

Doubles - input

14.0184849945

Doubles - output

14.01

Integer – input

13

Integer - output

13 (not 13.00)

Is there any way to implement it in the same decimalformat instance? My code is as follows, so far:

DecimalFormat df = new DecimalFormat("#,###,##0.00");
DecimalFormatSymbols otherSymbols = new   DecimalFormatSymbols(Locale.ENGLISH);
otherSymbols.setDecimalSeparator('.');
otherSymbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(otherSymbols);

Solution

You can set 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);
    }

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>