zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Bean
    DI
    require import export
    JSON转js
    vue路由相关
    JS引号区别
    Go语言系列之标准库strconv
    Go语言系列之标准库flag
    Go语言系列之并发编程
    Go语言系列之自定义实现日志库
  • 原文地址:https://www.cnblogs.com/lukexwang/p/4593150.html
Copyright © 2011-2022 走看看