double两位小数 java,格式,double的两位小数和在java中的整数的0

I am trying to format a double to exact 2 decimal places if it has fraction, and cut it off otherwise using DecimalFormat

So, I'd like to achieve next results:

100.123 -> 100.12

100.12 -> 100.12

100.1 -> 100.10

100 -> 100

Variant #1

DecimalFormat("#,##0.00")

100.1 -> 100.10

but

100 -> 100.00

Variant #2

DecimalFormat("#,##0.##")

100 -> 100

but

100.1 -> 100.1

Have any ideas what pattern to choose in my case?

解决方案

The only solution i reached is to use if statement like was mentioned here: https://stackoverflow.com/a/39268176/6619441

public static boolean isInteger(BigDecimal bigDecimal) {

int intVal = bigDecimal.intValue();

return bigDecimal.compareTo(new BigDecimal(intVal)) == 0;

}

public static String myFormat(BigDecimal bigDecimal) {

String formatPattern = isInteger(bigDecimal) ? "#,##0" : "#,##0.00";

return new DecimalFormat(formatPattern).format(bigDecimal);

}

Testing

myFormat(new BigDecimal("100")); // 100

myFormat(new BigDecimal("100.1")); // 100.10

If someone knows more elegant way, please share it!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值