BigDecimal


api: java.math

构造方法

BigDecimal(double val)

BigDecimal(String val);//处理小数精度的问题

常用方法

  1. BigDecimal add(BigDecimal augend)
    返回 BigDecimal ,其值是 (this + augend) ,其标为 max(this.scale(), augend.scale()) 。

  2. BigDecimal divide(BigDecimal divisor)

    除法

  3. BigDecimal multiply(BigDecimal multiplicand)

    乘法

  4. BigDecimal subtract(BigDecimal subtrahend)

    减法

笔试题

在java开发中如何处理小数精度丢失的问题

需要使用到的是BigDecimal(String val);

package tech.aistar.day12;

import java.math.BigDecimal;

/**
 * 本类用来演示: 处理小数
 *
 * @author: success
 * @date: 2021/8/4 9:27 上午
 */
public class BigDecimalHandlerFloatDemo {
    public static void main(String[] args) {
        BigDecimal d1 = new BigDecimal("0.1");
        BigDecimal d2 = new BigDecimal(String.valueOf(0.2));

        BigDecimal result = d1.add(d2);

        //BigDecimal->double/String
        double resultDouble = result.doubleValue();
        System.out.println(resultDouble);

        System.out.println(result);
    }
}

BigInteger

笔试题 - 递归算法求阶乘

构造:BigInteger(String val);

public class BigIntegerDemo {
 public static void main(String[] args) {
     System.out.println(test(6));
 }

 public static BigInteger test(int n){
     if(n==1)
         return BigInteger.ONE;
     BigInteger current = new BigInteger(String.valueOf(n));
     return current.multiply(test(n-1));
 }
}

文章作者: 码农耕地人
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 码农耕地人 !
  目录