当前位置:网站首页>Pit using BigDecimal
Pit using BigDecimal
2022-07-07 09:46:00 【Keeling1720】
BigDecimal The pit of
BigDecimal It is often used by us to calculate some scenes that need accurate calculation , For example, calculation of amount . however ,BigDecimal There are also many unknown pits . below , Let's briefly introduce some common pits .
1、 Use valueOf() replace new BigDecimal
public static void main(String[] args) {
BigDecimal bigDecimal1 = new BigDecimal(0.01);
BigDecimal bigDecimal2 = BigDecimal.valueOf(0.01);
System.out.println(bigDecimal1);
System.out.println(bigDecimal2);
}
The output is :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-mwyC8uaE-1656647473350)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1656565943063.png)]](/img/dd/d9b2e37afaff0e323516dc0332dba2.png)
You can see , direct new BigDecimal Pass in 0.01 When , because 0.01 This digital computer cannot accurately express , Cause it to be passed into BigDecimal Precision has been lost in . There is an error in the final output . and valueOf Is different , His bottom will Double Convert to String, Ensure that his accuracy will not be lost .
public static BigDecimal valueOf(double val) {
return new BigDecimal(Double.toString(val));
}
summary : Try to use string form to construct BigDecimal object , If it doesn't work , Then please also use BigDecimal.valueOf() Method to convert the value , To ensure our accuracy .
2、 Use compareTo instead of equals Compare
public static void main(String[] args) {
BigDecimal bigDecimal1 = new BigDecimal("1.0");
BigDecimal bigDecimal2 = new BigDecimal("1.00");
System.out.println(bigDecimal2.equals(bigDecimal1));
System.out.println(bigDecimal2.compareTo(bigDecimal1));
}
Running results :
Running results , Use equals Compare two BigDecimal The value of will be equal to false, because BigDecimal Of equals Will compare the accuracy of two numbers , and compareTo Method will only compare the size of two numbers .
summary : Use compareTo instead of equals Compare the two BigDecimal Value .
3、BigDecimal Not infinite precision
public static void main(String[] args) {
BigDecimal bigDecimal1 = new BigDecimal("1.0");
BigDecimal bigDecimal2 = new BigDecimal("3.0");
bigDecimal1.divide(bigDecimal2);
}
The operation results are as follows :
This is because ,1 / 3 be equal to Infinitely recurring decimals (0.33333… ). This is the time , We must tell JVM, We don't need the most accurate results . Change the code to :
public static void main(String[] args) {
BigDecimal bigDecimal1 = new BigDecimal("1.0");
BigDecimal bigDecimal2 = new BigDecimal("3.0");
System.out.println(bigDecimal1.divide(bigDecimal2, RoundingMode.HALF_UP));
}
Running results :

4、 Turn into String Use the right method
public static void main(String[] args) {
BigDecimal bigDecimal = BigDecimal.valueOf(12345678902132123113213.12345678912345678);
// When necessary, , Use scientific counting
System.out.println(bigDecimal.toString());
// No scientific counting
System.out.println(bigDecimal.toPlainString());
// The method of recording numbers often used in engineering calculation , It's like scientific counting , But the requirement is 10 The power of must be 3 Multiple
System.out.println(bigDecimal.toEngineeringString());
}
Running results :
summary :
- toString(): If necessary , Use scientific counting .
- toPlainString(): No scientific counting
- toEngineeringString(): The method of recording numbers often used in engineering calculation , It's like scientific counting , But the requirement is 10 The power of must be 3 Multiple
边栏推荐
- iNFTnews | 时尚品牌将以什么方式进入元宇宙?
- **grafana安装**
- PostgreSQL创建触发器的时候报错,
- Use 3 in data modeling σ Eliminate outliers for data cleaning
- flinkcdc采集oracle在snapshot阶段一直失败,这个得怎么调整啊?
- 【frida实战】“一行”代码教你获取WeGame平台中所有的lua脚本
- The difference between viewpager2 and viewpager and the implementation of viewpager2 in the rotation chart
- Netease Cloud Wechat applet
- Unity shader (to achieve a simple material effect with adjustable color attributes only)
- Create an int type array with a length of 6. The values of the array elements are required to be between 1-30 and are assigned randomly. At the same time, the values of the required elements are diffe
猜你喜欢

Over 100000 words_ Ultra detailed SSM integration practice_ Manually implement permission management
![[bw16 application] Anxin can realize mqtt communication with bw16 module / development board at instruction](/img/7f/d0917366c68865222154d82b9e7b40.png)
[bw16 application] Anxin can realize mqtt communication with bw16 module / development board at instruction

基于智慧城市与储住分离数字家居模式垃圾处理方法

Binary tree high frequency question type

Software modeling and analysis

CSDN salary increase technology - learn about the use of several common logic controllers of JMeter

Lecture 1: stack containing min function

4、 Fundamentals of machine learning

H5网页播放器EasyPlayer.js如何实现直播视频实时录像?

AI从感知走向智能认知
随机推荐
Pick up the premise idea of programming
Over 100000 words_ Ultra detailed SSM integration practice_ Manually implement permission management
esp8266使用TF卡并读写数据(基于arduino)
VSCode+mingw64
VSCode+mingw64+cmake
Lecture 1: stack containing min function
NETCORE 3.1 solves cross domain problems
Unity3d interface is embedded in WPF interface (mouse and keyboard can respond normally)
Oracle安装增强功能出错
shake数据库中怎么使用Mongo-shake实现MongoDB的双向同步啊?
Unity uses mesh to realize real-time point cloud (II)
Upload taro pictures to Base64
scrapy爬虫mysql,Django等
数据建模中利用3σ剔除异常值进行数据清洗
Lesson 1: finding the minimum of a matrix
JS逆向教程第一发
2020CCPC威海 J - Steins;Game (sg函数、线性基)
Unity shader (data type in cghlsl)
golang select机制和超时问题怎么解决
JS judge whether checkbox is selected in the project