gpt4 book ai didi

Java Math RoundingMode.HALF_EVEN 不同的结果

转载 作者:搜寻专家 更新时间:2023-11-01 01:40:09 30 4
gpt4 key购买 nike

看来 HALF_EVEN 舍入模式在 Java DecimalFormat 中的工作方式与 BigDecimal 不同。有没有办法使 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.25521.255
  • 小一点
  • double 21.26521.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

关于Java Math RoundingMode.HALF_EVEN 不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49899854/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com