如果基本的整数和浮点数精度不能够满足需求,看到给的数大于10^18, 那么可以使用java.math 包中的两个很有用的类:Biglnteger 和 BigDecimaL 这两个类可以处理包含任意长度数字序列的数值。
Biglnteger类实现了任意精度的整数运算, BigDecimal 实现了任意精度的浮点数运算。
1. java.math.BigInteger
常用操作:
• Biglnteger add(Biglnteger other) 返回这个大整数和另一个的和
• Biglnteger subtract(Biglnteger other) 返回这个大整数和另一个的差
• Biglnteger multipiy(Biginteger other) 返回这个大整数和另一个的积
• Biglnteger divide(Biglnteger other) 返回这个大整数和另一个的商
• Biglnteger mod(Biglnteger other) 返回这个大整数和另一个的余数
• int compareTo(Biglnteger other) 如果这个大整数与另一个大整数相等, 返回 0; 如果这个大整数小于另一个大整 数 other, 返回负数; 否则, 返回正数。
• static Biglnteger valueOf(long x) 返回值等于 x 的大整数。 (静态函数valueOf的参数只能是long类型的)
BigInteger(String val); 将指定字符串转换为十进制表示形式;
BigInteger(String val,int radix); 将指定基数的 BigInteger 的字符串表示形式转换为 BigInteger
求两个数的差
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
BigInteger a=sc.nextBigInteger();
BigInteger b=sc.nextBigInteger();
System.out.println(a.subtract(b));
}
}
2.java.math.BigDecimal
基本上和整数的一样
• BigDecimal divide(BigDecimal other RoundingMode mode)
要想计算商, 必须给出舍入方式 。RoundingMode.HALF_UP 一种方式 (BP, 数值 0 到 4 舍去, 数值 5 到 9 进位) 。
static BigDecimal valueOf(long x)
• static BigDecimal valueOf(double x)
• static BigDecimal valueOf(long x,int scale)
返回值为 x 或 x / 10scale 的一个大实数。
关于舍入方式参考:点我