java - 比较 BigDecimal

标签 java

我有以下两个 BigDecimal 对象。

    BigDecimal one = new BigDecimal(3.0);
    BigDecimal two = new BigDecimal(3.00);

    System.out.println(one.scale());//0
    System.out.println(two.scale());//0
    System.out.println(one.equals(two));//true

我已经阅读了 JavaDocs,但是无法理解 equalscompareTo 方法之间的区别。 JavaDoc 说这些对象不等于 equals 方法,结果必须是 false,但结果是 true。我很困惑。

最佳答案

您需要使用 String 构造函数来获得正确的比例,因为 BigDecimal(double)将获得尽可能小的规模

translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. The scale of the returned BigDecimal is the smallest value such that (10scale × val) is an integer.

关于文档的更精确:

BigDecimal.equals(Object)

Compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

BigDecimal.compareTo(BigDecimal)

Compares this BigDecimal with the specified BigDecimal. Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) 0), where is one of the six comparison operators.

您会发现 equals 使用比例进行比较,给出一些“奇怪”的结果。

BigDecimal bd1 = new BigDecimal("2"); //scale 0
BigDecimal bd2 = new BigDecimal("2.00"); //scale 2

bd1.equals(bd2); //false
bd1.compareTo(bd2); //0 => which means equivalent

关于java - 比较 BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48881976/

相关文章:

Java GUI : JLabel as Bullet should fly through Jpanel, 仅给出 "result"

java - 将日期时间设置为特定值

java - Cassandra - 许多小节点或更少的大节点?

java - 将 MouseListener 添加到 Zest Graph

java - 在 Java 中缓存 map

java - 与 Hadoop MapReduce 的成对比较

java - 使用什么样的数据结构(固定长度)?

java - 如何将多个文件从 hdfs 上传到单个 s3 文件?

java - 线程和并发

从 AWS Linux AMI 发送时出现 javax.mail.AuthenticationFailedException