• java学习笔记——大数据操作类


    java.math包中提供了两个大数字操作类:BigInteger(大整数操作类) BigDecimal(大小数操作类).

    • 大整数操作类:BigInteger

    BigInteger类构造方法:public BigInteger(String val)

    常用方法:public BigInteger add(BigInteger val)

    public BigInteger subtract(BigInteger val)

    public BigInteger multiply(BigInteger val)

    public BigInteger divide(BigInteger val)

    public BigInteger[] divideAndRemainder(BigInteger val):第一个数是商第二个数为余数

    public BigInteger pow(int exponent)返回其值为 (thisexponent) 的 BigInteger。注意,exponent 是一个整数而不是 BigInteger。

    以上代码在实际运用中用途并不大,在工作中如果遇到数学问题记得找第三方的开发包。

    • 大小数操作类:BigDecimal

    基本方法和操作和BigInteger相同,但BigDecimal扩展了一个非常重要的方法:

    Math类中的round()方法进行四舍五入操作过程中采用的是将小数点全部省略的做法,但这种做法在实际用途中并不可取。所以Math.roucnd()是一个没什么实际用途的方法,这时候只能利用BigDecimal类完成。

    BigDecimal中提供了一个除法操作:public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)

    divisor:被除数

    scale:保留的小数位数

    roundingMode:进位模式

    (public static final int ROUND_HALF_UP  

    public static final int ROUND_HALF_DOWN

    class MyMath{
        public static double round(double num,int scale){
            BigDecimal big=new BigDecimal(num);
            BigDecimal res=big.divide(new BigDecimal(1), scale, BigDecimal.ROUND_HALF_UP);//四舍五入所以括号中使用new BigDecimal(1)
            return res.doubleValue();
        }
    }
    public class BigDecimalDemo {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            System.out.println(MyMath.round(178.1436534, 6));
            System.out.println(MyMath.round(178.1436534, 3));
            System.out.println(MyMath.round(178.1436534, 0));
        }
    }
    View Code
  • 相关阅读:
    tomcat createSecureRandom 花费了将近10分钟
    tcpdump取数据保存
    Linux TOP命令 按内存占用排序和按CPU占用排序
    在四合院里写code是什么体验(非拉仇恨)
    严重的抑郁与焦虑症
    CodeIgniter 下引入ORM Doctrine
    linux下解压
    ssh 使用密钥与登录进行远程cp
    mac os 下的sublime --- 快捷键
    pixelmator处理png图片,处理掉过白的留白。
  • 原文地址:https://www.cnblogs.com/lukexwang/p/4593150.html
Copyright © 2020-2023  润新知