BigDecimal比较大小问题

本文详细介绍了Java中BigDecimal类的比较方法compareTo的使用。通过实例解释了如何正确判断两个BigDecimal对象是否相等,尤其是在它们数值相同但精度不同的情况下。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BigDecimal比较大小
   这个类是Java里精确计算的类,下面说一下两个BigDecimal对象大小,相等的判断
   1比较对象是否相等
     一般的对象用于等于,但是BigDecimal比较特殊,举个例子:
     BigDecimal a = BigDecimal.valueOf(1.0); 
     BigDecimal b = BigDecimal.valueOf(1.000); 

     在现实中这两个数字是相等的,但是如果用a.equals 
     (b)结果是假的;怎么不相等了呢?因为等于是比较内容,“1.0”和“1.000”当然不一样了

     解决办法:

            if(a.compareTo(b)== 0)结果是true

compareTo就是比较两个值,如果前者大于后者,返回1,等于返回0,小于返回-1,我下面给出了例子,由于比较的变量我用的是int,int型可以直接比较,所有没有用到compareTo比较,如果声明的是Date、String、Integer或者其他的,可以直接使用compareTo比较,



/**
 * Compares this {@code BigDecimal} with the specified
 * {@code BigDecimal}.  Two {@code 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 ({@literal <}, ==,
 * {@literal >}, {@literal >=}, !=, {@literal <=}).  The
 * suggested idiom for performing these comparisons is:
 * {@code (x.compareTo(y)} <<i>op</i>> {@code 0)}, where
 * <<i>op</i>> is one of the six comparison operators.
 *
 * @param  val {@code BigDecimal} to which this {@code BigDecimal} is
 *         to be compared.
 * @return -1, 0, or 1 as this {@code BigDecimal} is numerically
 *          less than, equal to, or greater than {@code val}.
 */
public int compareTo(BigDecimal val) {
    // Quick path for equal scale and non-inflated case.
    if (scale == val.scale) {
        long xs = intCompact;
        long ys = val.intCompact;
        if (xs != INFLATED && ys != INFLATED)
            return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
    }
    int xsign = this.signum();
    int ysign = val.signum();
    if (xsign != ysign)
        return (xsign > ysign) ? 1 : -1;
    if (xsign == 0)
        return 0;
    int cmp = compareMagnitude(val);
    return (xsign > 0) ? cmp : -cmp;
}

转自: 百度~( 千篇一律,感谢广大网友 )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值