zoukankan      html  css  js  c++  java
  • BigDecimal实现加减乘除

    一、BigDecimal构造方法(将其他类型转换成BigDecimal);

    1、 public BigDecimal(char[] in) {
            this(in, 0, in.length);
        }

    2、 public BigDecimal(String val) {
            this(val.toCharArray(), 0, val.length());
        }

    3、 public BigDecimal(String val, MathContext mc) {
            this(val.toCharArray(), 0, val.length(), mc);
        }

    4、 public BigDecimal(double val) {
            this(val,MathContext.UNLIMITED);
        }

    5、 public BigDecimal(BigInteger val) {
            scale = 0;
            intVal = val;
            intCompact = compactValFor(val);
        }

    6、 public BigDecimal(int val) {
            this.intCompact = val;
            this.scale = 0;
            this.intVal = null;
        }

    7、 public BigDecimal(long val) {
            this.intCompact = val;
            this.intVal = (val == INFLATED) ? INFLATED_BIGINT : null;
            this.scale = 0;
        }

    利用其构造方法客将不同类型的数字转换成BigDecimal类型的数字;

    二、利用BigDecimal实现加法(加法的方法)

     public BigDecimal add(BigDecimal augend) {
            if (this.intCompact != INFLATED) {
                if ((augend.intCompact != INFLATED)) {
                    return add(this.intCompact, this.scale, augend.intCompact, augend.scale);
                } else {
                    return add(this.intCompact, this.scale, augend.intVal, augend.scale);
                }
            } else {
                if ((augend.intCompact != INFLATED)) {
                    return add(augend.intCompact, augend.scale, this.intVal, this.scale);
                } else {
                    return add(this.intVal, this.scale, augend.intVal, augend.scale);
                }
            }
        }

    三、利用BegDecimal实现减法(减法的方法)

      public BigDecimal subtract(BigDecimal subtrahend) {
            if (this.intCompact != INFLATED) {
                if ((subtrahend.intCompact != INFLATED)) {
                    return add(this.intCompact, this.scale, -subtrahend.intCompact, subtrahend.scale);
                } else {
                    return add(this.intCompact, this.scale, subtrahend.intVal.negate(), subtrahend.scale);
                }
            } else {
                if ((subtrahend.intCompact != INFLATED)) {
                    // Pair of subtrahend values given before pair of
                    // values from this BigDecimal to avoid need for
                    // method overloading on the specialized add method
                    return add(-subtrahend.intCompact, subtrahend.scale, this.intVal, this.scale);
                } else {
                    return add(this.intVal, this.scale, subtrahend.intVal.negate(), subtrahend.scale);
                }
            }
        }

    四、利用BigDecimal实现乘法(乘法方法)

     public BigDecimal multiply(BigDecimal multiplicand) {
            int productScale = checkScale((long) scale + multiplicand.scale);
            if (this.intCompact != INFLATED) {
                if ((multiplicand.intCompact != INFLATED)) {
                    return multiply(this.intCompact, multiplicand.intCompact, productScale);
                } else {
                    return multiply(this.intCompact, multiplicand.intVal, productScale);
                }
            } else {
                if ((multiplicand.intCompact != INFLATED)) {
                    return multiply(multiplicand.intCompact, this.intVal, productScale);
                } else {
                    return multiply(this.intVal, multiplicand.intVal, productScale);
                }
            }
        }

    五、利用BigDecimal实现处罚(出发方法)

     public BigDecimal divide(BigDecimal divisor) {
            /*
             * Handle zero cases first.
             */
            if (divisor.signum() == 0) {   // x/0
                if (this.signum() == 0)    // 0/0
                    throw new ArithmeticException("Division undefined");  // NaN
                throw new ArithmeticException("Division by zero");
            }

            // Calculate preferred scale
            int preferredScale = saturateLong((long) this.scale - divisor.scale);

            if (this.signum() == 0) // 0/y
                return zeroValueOf(preferredScale);
            else {
                /*
                 * If the quotient this/divisor has a terminating decimal
                 * expansion, the expansion can have no more than
                 * (a.precision() + ceil(10*b.precision)/3) digits.
                 * Therefore, create a MathContext object with this
                 * precision and do a divide with the UNNECESSARY rounding
                 * mode.
                 */
                MathContext mc = new MathContext( (int)Math.min(this.precision() +
                                                                (long)Math.ceil(10.0*divisor.precision()/3.0),
                                                                Integer.MAX_VALUE),
                                                  RoundingMode.UNNECESSARY);
                BigDecimal quotient;
                try {
                    quotient = this.divide(divisor, mc);
                } catch (ArithmeticException e) {
                    throw new ArithmeticException("Non-terminating decimal expansion; " +
                                                  "no exact representable decimal result.");
                }

                int quotientScale = quotient.scale();

                // divide(BigDecimal, mc) tries to adjust the quotient to
                // the desired one by removing trailing zeros; since the
                // exact divide method does not have an explicit digit
                // limit, we can add zeros too.
                if (preferredScale > quotientScale)
                    return quotient.setScale(preferredScale, ROUND_UNNECESSARY);

                return quotient;
            }
        }

    以上为BigDecimal单参实现加减乘除的源码-------------------

    六、用例子实现加减乘除

    1. /**  
    2. * 提供精确的加法运算。  
    3. * @param v1 被加数  
    4. * @param v2 加数  
    5. * @return 两个参数的和  
    6. */  
    7. public static double add(double v1,double v2){   
    8. BigDecimal b1 = new BigDecimal(Double.toString(v1));   
    9. BigDecimal b2 = new BigDecimal(Double.toString(v2));   
    10. return b1.add(b2).doubleValue();   
    11. }   
    12. /**  
    13. * 提供精确的减法运算。  
    14. * @param v1 被减数  
    15. * @param v2 减数  
    16. * @return 两个参数的差  
    17. */  
    18. public static double sub(double v1,double v2){   
    19. BigDecimal b1 = new BigDecimal(Double.toString(v1));   
    20. BigDecimal b2 = new BigDecimal(Double.toString(v2));   
    21. return b1.subtract(b2).doubleValue();   
    22. }   
    23. /**  
    24. * 提供精确的乘法运算。  
    25. * @param v1 被乘数  
    26. * @param v2 乘数  
    27. * @return 两个参数的积  
    28. */  
    29. public static double mul(double v1,double v2){   
    30. BigDecimal b1 = new BigDecimal(Double.toString(v1));   
    31. BigDecimal b2 = new BigDecimal(Double.toString(v2));   
    32. return b1.multiply(b2).doubleValue();   
    33. }   
    34. /**  
    35. * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到  
    36. * 小数点以后10位,以后的数字四舍五入。  
    37. * @param v1 被除数  
    38. * @param v2 除数  
    39. * @return 两个参数的商  
    40. */  
    41. public static double div(double v1,double v2){   
    42. return div(v1,v2,DEF_DIV_SCALE);   
    43. }   
    44. /**  
    45. * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指  
    46. * 定精度,以后的数字四舍五入。  
    47. * @param v1 被除数  
    48. * @param v2 除数  
    49. * @param scale 表示表示需要精确到小数点以后几位。  
    50. * @return 两个参数的商  
    51. */  
    52. public static double div(double v1,double v2,int scale){   
    53. if(scale<0){   
    54. throw new IllegalArgumentException(   
    55. "The scale must be a positive integer or zero");   
    56. }   
    57. BigDecimal b1 = new BigDecimal(Double.toString(v1));   
    58. BigDecimal b2 = new BigDecimal(Double.toString(v2));   
    59. return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();   
    60. }  

    ***BigDecimal中的compareTo方法

    BigDecimal a = new BigDecimal("1.00");
    BigDecmial b = new BigDecimal(1);
    想比较一下a和b的大小,一般都会用equals
    System.out.println(a.equals(b));
    但是输出结果是:false
    原因是:BigDecimal比较时,不仅比较值,而且还比较精度?
    if(a.compareTo(b)==0) 结果是true
    比较大小可以用 a.compareTo(b)
    返回值 -1 小于 0 等于 1 大于
  • 相关阅读:
    查看SQL Server版本号(2005 & 2008)
    Installing an App for Testing
    Viewstate 的用法
    How to Open the Pdf file?
    工具类:Log
    SPSiteDataQuery and SPQuery
    SPSite, SPWeb Dispose and Class Design Partter
    Add Properties or Delete List Folder Content Type
    SharePoint UserControl
    Click Once 布署
  • 原文地址:https://www.cnblogs.com/wwwcf1982603555/p/9051054.html
Copyright © 2011-2022 走看看