java format 小数,Java:使用DecimalFormat格式化双精度和整数,但保留不带小数分隔符的整数...

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 handling integers I want the program to keep them unaffected. In other words:

Doubles - Input

14.0184849945

Doubles - Output

14.01

Integers - Input

13

Integers - Output

13 (not 13.00)

Is there a way to implement this in the same DecimalFormat instance? My code is the following, so far:

DecimalFormat df = new DecimalFormat("#,###,##0.00");

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH);

otherSymbols.setDecimalSeparator('.');

otherSymbols.setGroupingSeparator(',');

df.setDecimalFormatSymbols(otherSymbols);

解决方案

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值