Java语言学习总结——基础篇——大数值的表示

Java语言学习

大数值

在实际编程中经常遇到整数和浮点数精度不能满足需求的情况,比如要表示一个很大的数,或者表示一个精度非常高的数,可以使用java.math包中的BigIntegerBigDecimal两个类,这两个类可以处理任意长度的数字。

定义格式:

		BigInteger a = BigInteger.valueOf(1234567890);
		BigDecimal b = BigDecimal.valueOf(1.234567891111111);

初始化时valueOf只能传递不大于10位的整数以及总位数小于18位的浮点型。

		public static void main(String[] args) {
		BigInteger a = BigInteger.valueOf(1234567890);
		BigDecimal b = BigDecimal.valueOf(10000.234567891111111);
		BigDecimal c = BigDecimal.valueOf(10001111111.2345678911111111111);
		System.out.println(a);
		System.out.println(b);
		System.out.println(c);
	}

运行结果如下:
在这里插入图片描述

运算

大树值不能直接用 **+ - * /**符合进行运算,需要调用相应的方法进行计算。

类型方法作用
Biglntegeradd(Biglnteger other)整数加
Biglntegersubtract(Biglnteger other)整数减
Biglntegermultipiy(Biginteger other)整数乘
Biglntegerdivide(Biglnteger other)整数除
Biglntegermod(Biglnteger other)取余数
Biglntegerint compareTo(Biglnteger other)比较两个数是否相等,相等返回0,否则返回整数
Biglntegerstatic Biglnteger valueOf(long x)返回值等于x的大整数
BigDecimaladd(BigDecimal other)浮点数加
BigDecimalsubtract(BigDecimal other)浮点数减
BigDecimalmultipiy(BigDecimal other)浮点数乘
BigDecimaldivide(BigDecimal other RoundingMode mode)
BigDecimalint compareTo(BigDecimal other)比较
BigDecimalstatic BigDecimal valueOf(1ong x)
BigDecimalstatic BigDecimal valueOf(1ong x,int scale)返回值为 X 或 x / 10scale 的一个大实数

代码示例:

public static void main(String[] args) {
		BigInteger a = BigInteger.valueOf(1234567890);
		BigDecimal b = BigDecimal.valueOf(10000.234567891111111);
		a=a.multiply(BigInteger.valueOf(11111111));
		a=a.multiply(BigInteger.valueOf(11111111));
		a=a.multiply(BigInteger.valueOf(11111111));
		a=a.multiply(BigInteger.valueOf(11111111));
		a=a.multiply(BigInteger.valueOf(11111111));
		a=a.multiply(BigInteger.valueOf(11111111));
		a=a.multiply(BigInteger.valueOf(11111111));
		a=a.multiply(BigInteger.valueOf(11111111));
		a=a.multiply(BigInteger.valueOf(11111111));
		a=a.multiply(BigInteger.valueOf(11111111));
		a=a.multiply(BigInteger.valueOf(11111111));
		a=a.multiply(BigInteger.valueOf(11111111));
		BigDecimal c = BigDecimal.valueOf(10001111111.2345678911111111111);
		System.out.println(a);
		System.out.println(b);
		System.out.println(c);
		
	}

输出结果:
在这里插入图片描述
输出结果为大数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值