Java基础之数字处理工具 大数运算 小数运算 取小数位

本文介绍Java中处理大数运算的BigInteger和BigDecimal类,以及如何使用DecimalFormat类精确控制数字显示格式,适合需要高精度计算的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数字处理工具类

BigInteger:可以让超过Integer范围内的数据进行运算。

构造方法: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)

BigDecimal:由于在运算的时候,float类型和double很容易丢失精度,为了能精确的表示、计算浮点数,Java提供了BigDecimal,不可变的、任意精度的有符号十进制数。
构造方法:public BigDecimal(String val)
常用方法:
public BigDecimal add(BigDecimal augend)
public BigDecimal subtract(BigDecimal subtrahend)
public BigDecimal multiply(BigDecimal multiplicand)
public BigDecimal divide(BigDecimal divisor)
除小数时 可能有除不尽的情况 请上网查阅相关方法 处理相关问题

在这里插入图片描述

取小数位 DecimalFormat:Java 提供 DecimalFormat类,帮你用最快的速度将数字格式化为你需要的样子。

例如,取2位小数。

示例:
double pi=3.1415927; //圆周率
//取一位整数,结果:3
System.out.println(new DecimalFormat(“0”).format(pi));
//取一位整数和两位小数,结果3.14
System.out.println(new DecimalFormat(“0.00”).format(pi)); 
//取两位整数和三位小数,整数不足部分以0填补,结果:03.142
System.out.println(new DecimalFormat(“00.000”).format(pi));
//取所有整数部分,结果:3
System.out.println(new DecimalFormat("#").format(pi));
//以百分比方式计数,并取两位小数,结果:314.16%
System.out.println(new DecimalFormat("#.##%").format(pi));
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值