小编Sum*_*man的帖子

Java Math RoundingMode.HALF_EVEN不同的结果

看来,HALF_EVEN舍入模式在Java中的工作方式不同DecimalFormatBigDecimal.有什么办法DecimalFormat可以保持一致吗?

// Using BigDecimal scale
System.out.println("Big decimal scale (HALF_EVEN) of 21.255 ==> " + new BigDecimal("21.255").setScale(2, RoundingMode.HALF_EVEN));
System.out.println("Big decimal scale (HALF_EVEN) of 21.265 ==> " + new BigDecimal("21.265").setScale(2, RoundingMode.HALF_EVEN));

// Using DecimalFormat
DecimalFormat cdf = new DecimalFormat("#,##0.00");
cdf.setRoundingMode(RoundingMode.HALF_EVEN); // default anyway
System.out.println("Decimal format (HALF_EVEN) of 21.255 ==> " + cdf.format(21.255));
System.out.println("Decimal format (HALF_EVEN) of 21.265 ==> " + cdf.format(21.265));

Output:
Big decimal scale (HALF_EVEN) of 21.255 ==> 21.26
Big decimal scale (HALF_EVEN) …
Run Code Online (Sandbox Code Playgroud)

java double rounding bigdecimal decimalformat

4
推荐指数
1
解决办法
381
查看次数

标签 统计

bigdecimal ×1

decimalformat ×1

double ×1

java ×1

rounding ×1