JAVA学习->大数值

 一、大数值类的介绍 

       今天,学习一下java.math包中两个很有用的类:BigInteger和BigDecimal,如果基本的整数和浮点数精度不能够满足需求,这两个类可以处理任意长度数字序列的数值。BigInteger类实现了任意精度的整数运算,BigDecimal类实现了任意精度的浮点运算。

       使用静态的valueOf方法可以将普通的数值转换成大数值。遗憾的是,不能使用我们熟悉的算术运算符(+和*)处理大数据,而需要使用其提供的方法实现运算。与C++不同,Java没有提供运算符重载的功能,Java语言确实为字符串的连接重载了+运算符,但没有重载其它的运算,也没有提供Java程序员在自己的类中重载运算符的机会。

二、API

1、java.math.BigInteger

        BigInteger   add  (BigInteger  other);

        BigInteger   subtract  (BigInteger  other);

        BigInteger   multiply  (BigInteger  other);

        BigInteger   divide  (BigInteger  other);

        BigInteger   mod  (BigInteger  other);

        以上5个方法分别实现了一个大整数和另一个大整数(other)的和、差、乘、除、取模操作(余数)。

        

        int   compareTo  (BigInteger  other);

        如果这个大整数与另一个大整数other相等,返回0;如果这个大整数小于另一个大整数,返回负数,否则,返回正数。

        static   BigInteger    valueOf  (long x);   

        返回等于x的大整数。


2、java.math.BigDecimal

         BigDecimal   add  (BigDecimal  other);

        BigDecimal   subtract  (BigDecimal  other);

        BigDecimal   multiply  (BigDecimal  other);

        BigDecimal   divide  (BigDecimal  other,RoundingMode   mode);

        以上5个方法分别实现了一个大整数和另一个大整数(other)的和、差、乘、除操作。要想计算商,必须给出舍入方式(RoundingMode),RoundingMode.HALF_UP是四舍五入方式,即:0到4舍去,5到9进位。它适用于常规的计算,有关其他的舍入方法请参看API文档。

        

        int   compareTo  (BigDecimal  other);

        如果这个大实数与另一个大实数other相等,返回0;如果这个大实数小于另一个大实数,返回负数,否则,返回正数。

        static   BigDecimal    valueOf  (long x);   

        static   BigDecimal    valueOf  (long x, int  scale);   

        返回等于x或x/(10^scale)的大实数。



    

猜你喜欢

转载自blog.csdn.net/wuyileiju__/article/details/80554323