java.math.BigDecimal简介

目录

一、BigDecimal概述

二、BigDecimal常用构造函数

2.1.常用构造函数 

 2.2.使用问题分析

2.2.1.使用示例: 

 2.2.2.结果示例:

2.2.3.结果分析

2.3.使用问题 

2.3.1.使用示例 

2.3.2.结果示例 

2.3.3.结果分析 

三、BigDecimal常用方法详解

3.1.常用方法 

3.2.BigDecimal大小比较 

四、BigDecimal格式化

五、BigDecimal常见问题

 5.1.除法的时候出现异常

5.1.1.异常 

5.1.2.原因分析:

5.1.3.解决方法:

5.1.4. 设置舍入模式

 5.2.数据操作后设置取舍模式

 5.2.1.代码示例

 5.2.2.解释

5.2.3. setScale

六、BigDecimal总结

6.1.总结


一、BigDecimal概述

        Java在java.math包中提供的API类BigDecimal,用来对超过16位有效位的数进行精确的运算。双精度浮点型变量double可以处理16位有效数,但在实际应用中,可能需要对更大或者更小的数进行运算和处理。

        一般情况下,对于那些不需要准确计算精度的数字,我们可以直接使用Float和Double处理,但是Double.valueOf(String) 和Float.valueOf(String)会丢失精度。所以开发中,如果我们需要精确计算的结果,则必须使用BigDecimal类来操作。

        BigDecimal所创建的是对象,故我们不能使用传统的+、-、*、/等算术运算符直接对其对象进行数学运算,而必须调用其相对应的方法。方法中的参数也必须是BigDecimal的对象。构造器是类的特殊方法,专门用来创建对象,特别是带有参数的对象。

二、BigDecimal常用构造函数

2.1.常用构造函数 

  • BigDecimal(int)

        创建一个具有参数所指定整数值的对象

  • BigDecimal(double)(不推荐)

        创建一个具有参数所指定双精度值的对象

  • BigDecimal(long)(不推荐)

        创建一个具有参数所指定长整数值的对象

  • BigDecimal(String)

        创建一个具有参数所指定以字符串表示的数值的对象

 2.2.使用问题分析

2.2.1.使用示例: 

        BigDecimal a =new BigDecimal(0.1);
        System.out.println("a values is:"+a);
        System.out.println("=====================");
        BigDecimal b =new BigDecimal("0.1");
        System.out.println("b values is:"+b);
        System.out.println("=====================");
        System.out.println("=====================");
        BigDecimal c =new BigDecimal(3.1d);
        System.out.println("c values is:"+c);
        System.out.println("=====================");
        BigDecimal d =new BigDecimal(3.1f);
        System.out.println("d values is:"+d);

 2.2.2.结果示例:

a values is:0.1000000000000000055511151231257827021181583404541015625
=====================
b values is:0.1
=====================
=====================
c values is:3.100000000000000088817841970012523233890533447265625
=====================
d values is:3.099999904632568359375

2.2.3.结果分析

        1)参数类型为double的构造方法的结果有一定的不可预知性。有人可能认为在Java中写入newBigDecimal(0.1)所创建的BigDecimal正好等于 0.1(非标度值 1,其标度为 1),但是它实际上等于0.1000000000000000055511151231257827021181583404541015625。这是因为0.1无法准确地表示为 double(或者说对于该情况,不能表示为任何有限长度的二进制小数)。这样,传入到构造方法的值不会正好等于 0.1(虽然表面上等于该值)。

        2)String 构造方法是完全可预知的:写入 newBigDecimal(“0.1”) 将创建一个 BigDecimal,它正好等于预期的 0.1。因此,比较而言, 通常建议优先使用String构造方法。

        3)当double必须用作BigDecimal的源时,请注意,此构造方法提供了一个准确转换;它不提供与以下操作相同的结果:先使用Double.toString(double)方法,然后使用BigDecimal(String)构造方法,将double转换为String。要获取该结果,请使用static valueOf(double)方法。

2.3.使用问题 

2.3.1.使用示例 

        BigDecimal c =new BigDecimal(99.99d);
        System.out.println("c values is:"+c);
        System.out.println("c.doubleValue() = " + c.doubleValue());
        System.out.println("=====================");
        BigDecimal d =new BigDecimal(99.99f);
        System.out.println("d values is:"+d);
        System.out.println("d.floatValue() = " + d.floatValue());
        System.out.println("=====================");
        BigDecimal e =new BigDecimal("99.99");
        System.out.println("e values is:"+e);
        System.out.println("e.toString() = " + e.toString());

2.3.2.结果示例 

c values is:99.9899999999999948840923025272786617279052734375
c.doubleValue() = 99.99
=====================
d values is:99.98999786376953125
d.floatValue() = 99.99
=====================
e values is:99.99
e.toString() = 99.99

2.3.3.结果分析 

        由上述示例可以看出,在使用double和float类型的构造方法时,数值会出现误差;但使用其对应的方法时,则不会出现误差,因此,在日常工作时,类型选择推荐转化为String进行操作,防止出现误差。

三、BigDecimal常用方法详解

3.1.常用方法 

  • add(BigDecimal)

BigDecimal对象中的值相加,返回BigDecimal对象

  • subtract(BigDecimal)

BigDecimal对象中的值相减,返回BigDecimal对象

  • multiply(BigDecimal)

BigDecimal对象中的值相乘,返回BigDecimal对象

  • divide(BigDecimal)

BigDecimal对象中的值相除,返回BigDecimal对象

  • toString()

将BigDecimal对象中的值转换成字符串

  • doubleValue()

将BigDecimal对象中的值转换成双精度数

  • floatValue()

将BigDecimal对象中的值转换成单精度数

  • longValue()

将BigDecimal对象中的值转换成长整数

  • intValue()

将BigDecimal对象中的值转换成整数

3.2.BigDecimal大小比较 

         java中对BigDecimal比较大小一般用的是bigdemical的compareTo方法

int a = bigdemical.compareTo(bigdemical2)

         返回结果分析:

a = -1,表示bigdemical小于bigdemical2;
a = 0,表示bigdemical等于bigdemical2;
a = 1,表示bigdemical大于bigdemical2;

        举例:a大于等于b

new bigdemica(a).compareTo(new bigdemical(b)) >= 0

四、BigDecimal格式化

        由于NumberFormat类的format()方法可以使用BigDecimal对象作为其参数,可以利用BigDecimal对超出16位有效数字的货币值,百分值,以及一般数值进行格式化控制。

        以利用BigDecimal对货币和百分比格式化为例。首先,创建BigDecimal对象,进行BigDecimal的算术运算后,分别建立对货币和百分比格式化的引用,最后利用BigDecimal对象作为format()方法的参数,输出其格式化的货币值和百分比。

NumberFormat currency = NumberFormat.getCurrencyInstance(); //建立货币格式化引用
NumberFormat percent = NumberFormat.getPercentInstance();  //建立百分比格式化引用
percent.setMaximumFractionDigits(3); //百分比小数点最多3位

BigDecimal loanAmount = new BigDecimal("15000.48"); //贷款金额
BigDecimal interestRate = new BigDecimal("0.008"); //利率
BigDecimal interest = loanAmount.multiply(interestRate); //相乘

System.out.println("贷款金额:\t" + currency.format(loanAmount));
System.out.println("利率:\t" + percent.format(interestRate));
System.out.println("利息:\t" + currency.format(interest));

 结果:

贷款金额: ¥15,000.48 利率: 0.8% 利息: ¥120.00

 BigDecimal格式化保留2为小数,不足则补0:

public class NumberFormat {

    public static void main(String[] s){
        System.out.println(formatToNumber(new BigDecimal("3.435")));
        System.out.println(formatToNumber(new BigDecimal(0)));
        System.out.println(formatToNumber(new BigDecimal("0.00")));
        System.out.println(formatToNumber(new BigDecimal("0.001")));
        System.out.println(formatToNumber(new BigDecimal("0.006")));
        System.out.println(formatToNumber(new BigDecimal("0.206")));
    }
    /**
     * @desc 1.0~1之间的BigDecimal小数,格式化后失去前面的0,则前面直接加上0。
     * 2.传入的参数等于0,则直接返回字符串"0.00"
     * 3.大于1的小数,直接格式化返回字符串
     * @param obj传入的小数
     * @return
     */
    public static String formatToNumber(BigDecimal obj) {
        DecimalFormat df = new DecimalFormat("#.00");
        if(obj.compareTo(BigDecimal.ZERO)==0) {
            return "0.00";
        }else if(obj.compareTo(BigDecimal.ZERO)>0&&obj.compareTo(new BigDecimal(1))<0){
            return "0"+df.format(obj).toString();
        }else {
            return df.format(obj).toString();
        }
    }
}

结果为:

3.44
0.00
0.00
0.00
0.01
0.21

五、BigDecimal常见问题

 5.1.除法的时候出现异常

5.1.1.异常 

java.lang.ArithmeticException: Non-terminating decimal expansion; 
no exact representable decimal result

5.1.2.原因分析:

通过BigDecimal的divide方法进行除法时当不整除,出现无限循环小数时,就会抛异常:java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

5.1.3.解决方法:

divide方法设置精确的小数点,如:divide(xxxxx,2) 

5.1.4. 设置舍入模式

        其实divide方法有可以传三个参数:public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) 第一参数表示除数, 第二个参数表示小数点后保留位数,第三个参数表示舍入模式,只有在作除法运算或四舍五入时才用到舍入模式,有下面这几种: 

    /**
     * Returns a {@code BigDecimal} whose value is {@code (this /
     * divisor)}, and whose scale is as specified.  If rounding must
     * be performed to generate a result with the specified scale, the
     * specified rounding mode is applied.
     *
     * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
     * should be used in preference to this legacy method.
     *
     * @param  divisor value by which this {@code BigDecimal} is to be divided.
     * @param  scale scale of the {@code BigDecimal} quotient to be returned.
     * @param  roundingMode rounding mode to apply.
     * @return {@code this / divisor}
     * @throws ArithmeticException if {@code divisor} is zero,
     *         {@code roundingMode==ROUND_UNNECESSARY} and
     *         the specified scale is insufficient to represent the result
     *         of the division exactly.
     * @throws IllegalArgumentException if {@code roundingMode} does not
     *         represent a valid rounding mode.
     * @see    #ROUND_UP
     *         向远离0的方向舍入
     * @see    #ROUND_DOWN
     *         向零方向舍入
     * @see    #ROUND_CEILING
     *         向正无穷方向舍入
     * @see    #ROUND_FLOOR
     *         向负无穷方向舍入
     * @see    #ROUND_HALF_UP
     *         向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,向上舍入,
     *         1.55保留一位小数结果为1.6
     * @see    #ROUND_HALF_DOWN
     *         向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,向下舍入,
     *         例如1.55 保留一位小数结果为1.5
     * @see    #ROUND_HALF_EVEN
     *         向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,
     *         如果保留位数是奇数,使用ROUND_HALF_UP
     *         如果是偶数,使用ROUND_HALF_DOWN
     * @see    #ROUND_UNNECESSARY
     *         计算结果是精确的,不需要舍入模式
     */
    public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
        if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
            throw new IllegalArgumentException("Invalid rounding mode");
        if (this.intCompact != INFLATED) {
            if ((divisor.intCompact != INFLATED)) {
                return divide(this.intCompact, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);
            } else {
                return divide(this.intCompact, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);
            }
        } else {
            if ((divisor.intCompact != INFLATED)) {
                return divide(this.intVal, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);
            } else {
                return divide(this.intVal, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);
            }
        }
    }

 5.2.数据操作后设置取舍模式

 5.2.1.代码示例

/**
     * 将字符串"元"转换成"分"  Long类型
     * @param str
     * @return
     */
    public static Long convertDollar2CentLong(String str) {
        return new BigDecimal(str)
                .multiply(new BigDecimal(100))
                .setScale(0, BigDecimal.ROUND_FLOOR)
                .longValue();
    }

        上面示例使用了匿名函数链式编程。 

 5.2.2.解释

         上面就是一个“元”转“分”的示例,作用是将字符串表示的数字乘以100,并将结果转换成long类型。具体解释如下:

  1. new BigDecimal(str) 用于将字符串 str 转换成 BigDecimal 对象。BigDecimal 对象是一种高精度的数字表示方法,可以避免使用浮点数时出现的精度问题。
  2. multiply(new BigDecimal(100)) 用于将 BigDecimal 对象乘以 100。
  3. setScale(0, BigDecimal.ROUND_FLOOR) 用于将结果保留0位小数,并采用向下取整的方式舍入。
  4. longValue() 用于将 BigDecimal 对象转换成 long 类型的整数。

        综合起来,这行代码的作用就是将一个字符串表示的数字乘以100后转换成整数。例如,对于输入的字符串 "3.14",经过这行代码处理后得到的结果将是 314。

5.2.3. setScale

         保留参数介绍同5.1.4,源码如下:

    /**
     * Returns a {@code BigDecimal} whose scale is the specified
     * value, and whose unscaled value is determined by multiplying or
     * dividing this {@code BigDecimal}'s unscaled value by the
     * appropriate power of ten to maintain its overall value.  If the
     * scale is reduced by the operation, the unscaled value must be
     * divided (rather than multiplied), and the value may be changed;
     * in this case, the specified rounding mode is applied to the
     * division.
     *
     * <p>Note that since BigDecimal objects are immutable, calls of
     * this method do <i>not</i> result in the original object being
     * modified, contrary to the usual convention of having methods
     * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
     * Instead, {@code setScale} returns an object with the proper
     * scale; the returned object may or may not be newly allocated.
     *
     * <p>The new {@link #setScale(int, RoundingMode)} method should
     * be used in preference to this legacy method.
     *
     * @param  newScale scale of the {@code BigDecimal} value to be returned.
     * @param  roundingMode The rounding mode to apply.
     * @return a {@code BigDecimal} whose scale is the specified value,
     *         and whose unscaled value is determined by multiplying or
     *         dividing this {@code BigDecimal}'s unscaled value by the
     *         appropriate power of ten to maintain its overall value.
     * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}
     *         and the specified scaling operation would require
     *         rounding.
     * @throws IllegalArgumentException if {@code roundingMode} does not
     *         represent a valid rounding mode.
     * @see    #ROUND_UP
     * @see    #ROUND_DOWN
     * @see    #ROUND_CEILING
     * @see    #ROUND_FLOOR
     * @see    #ROUND_HALF_UP
     * @see    #ROUND_HALF_DOWN
     * @see    #ROUND_HALF_EVEN
     * @see    #ROUND_UNNECESSARY
     */
    public BigDecimal setScale(int newScale, int roundingMode) {
        if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
            throw new IllegalArgumentException("Invalid rounding mode");

        int oldScale = this.scale;
        if (newScale == oldScale)        // easy case
            return this;
        if (this.signum() == 0)            // zero can have any scale
            return zeroValueOf(newScale);
        if(this.intCompact!=INFLATED) {
            long rs = this.intCompact;
            if (newScale > oldScale) {
                int raise = checkScale((long) newScale - oldScale);
                if ((rs = longMultiplyPowerTen(rs, raise)) != INFLATED) {
                    return valueOf(rs,newScale);
                }
                BigInteger rb = bigMultiplyPowerTen(raise);
                return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);
            } else {
                // newScale < oldScale -- drop some digits
                // Can't predict the precision due to the effect of rounding.
                int drop = checkScale((long) oldScale - newScale);
                if (drop < LONG_TEN_POWERS_TABLE.length) {
                    return divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode, newScale);
                } else {
                    return divideAndRound(this.inflated(), bigTenToThe(drop), newScale, roundingMode, newScale);
                }
            }
        } else {
            if (newScale > oldScale) {
                int raise = checkScale((long) newScale - oldScale);
                BigInteger rb = bigMultiplyPowerTen(this.intVal,raise);
                return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);
            } else {
                // newScale < oldScale -- drop some digits
                // Can't predict the precision due to the effect of rounding.
                int drop = checkScale((long) oldScale - newScale);
                if (drop < LONG_TEN_POWERS_TABLE.length)
                    return divideAndRound(this.intVal, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode,
                                          newScale);
                else
                    return divideAndRound(this.intVal,  bigTenToThe(drop), newScale, roundingMode, newScale);
            }
        }
    }

六、BigDecimal总结

6.1.总结

        在需要精确的小数计算时再使用BigDecimal,BigDecimal的性能比double和float差,在处理庞大,复杂的运算时尤为明显。故一般精度的计算没必要使用BigDecimal。尽量使用参数类型为String的构造函数。

        BigDecimal都是不可变的(immutable)的, 在进行每一次四则运算时,都会产生一个新的对象 ,所以在做加减乘除运算时要记得要保存操作后的值。

猜你喜欢

转载自blog.csdn.net/weixin_52255395/article/details/131660040