Java:使用DecimalFormat格式化双精度和整数,但保持整数不带小数分隔符

Lef*_*008 15 java double integer decimalformat

我正在尝试在Java程序中格式化一些数字.数字将是双精度数和整数数.处理双精度时,我想只保留两个小数点,但在处理整数时,我希望程序保持不受影响.换一种说法:

双打 - 输入

14.0184849945
Run Code Online (Sandbox Code Playgroud)

双打 - 输出

14.01
Run Code Online (Sandbox Code Playgroud)

整数 - 输入

13
Run Code Online (Sandbox Code Playgroud)

整数 - 输出

13 (not 13.00)
Run Code Online (Sandbox Code Playgroud)

有没有办法在同一个 DecimalFormat实例中实现它?到目前为止,我的代码如下:

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

Rod*_*aki 28

你可以设置minimumFractionDigits为0.像这样:

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

}
Run Code Online (Sandbox Code Playgroud)

  • 现在它的格式为 44.0 到 44 和 55.60 到 55.6 。如何使用格式保留末尾的零? (2认同)