繁体   English   中英

Java Math RoundingMode.HALF_EVEN不同的结果

[英]Java Math RoundingMode.HALF_EVEN different results

看起来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) of 21.265 ==> 21.26
Decimal format (HALF_EVEN) of 21.255 ==> 21.25
Decimal format (HALF_EVEN) of 21.265 ==> 21.27

如评论中所述,如果您尝试:

Double double1 = new Double(21.255);
BigDecimal bigDecimal1 = new BigDecimal(double1);
System.out.println(bigDecimal1);  //21.254999999999999005240169935859739780426025390625

Double double2 = new Double(21.265);
BigDecimal bigDecimal2 = new BigDecimal(double2);
System.out.println(bigDecimal2); //21.2650000000000005684341886080801486968994140625

你会发现:

  • double 21.255略低于21.255
  • double 21.265略高于21.265

您可以在使用DecimalFormat时将输入作为BigDecimal启动,以避免丢失准确性:

System.out.println("Decimal format (HALF_EVEN) of 21.255 ==> " + cdf.format(new BigDecimal("21.255")));
//21.26
System.out.println("Decimal format (HALF_EVEN) of 21.265 ==> " + cdf.format(new BigDecimal("21.265")));
//21.26

我刚刚进行了一些测试:使用@Mark Rotteveel解决方案:

cdf.format(new BigDecimal(21.255))

Big decimal scale (HALF_EVEN) of 21.255 ==> 21.26
Big decimal scale (HALF_EVEN) of 21.265 ==> 21.26
Decimal format (HALF_EVEN) of 21.255 ==> 21,25
Decimal format (HALF_EVEN) of 21.265 ==> 21,27 

使用BigDecimal String构造函数:

cdf.format(new BigDecimal("21.255"))

Big decimal scale (HALF_EVEN) of 21.255 ==> 21.26
Big decimal scale (HALF_EVEN) of 21.265 ==> 21.26
Decimal format (HALF_EVEN) of 21.255 ==> 21,26
Decimal format (HALF_EVEN) of 21.265 ==> 21,26

很明显,您必须使用String构造函数来获得正确的结果

21.255值不完全是21.255,它实际上更接近21.25499999... ,这意味着即使使用舍入模式HALF_EVEN ,它也会向下舍入到21.25 同样,双21.265实际上更接近21.26500000000000056...这意味着它将向上舍入。

通过使用new BigDecimal(double)而不是new BigDecimal(String)您可以获得与DecimalFormat完全相同的行为

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM