当前位置:网站首页>Improper use of BigDecimal caused P0 accident!
Improper use of BigDecimal caused P0 accident!
2022-06-10 05:37:00 【Program ape DD_】
Source of the article :https://c1n.cn/MSqAy
background
When we use the amount to calculate or display the amount, we often use BigDecimal, It is also a very recommended type when it comes to the amount .
BigDecimal It also provides many constructor methods , Improper use of these constructor methods may cause unnecessary trouble or even loss of money , Thus causing accident asset loss .
accident
Next, let's look at an accident at the cashier .
Problem description
The cashier reported an error in calculating the amount of goods , The order cannot be paid .
Accident level
P0
Accident process
as follows :
13:44, Get the alarm , Order payment failed , Payment availability reduced to 60%
13:50, Quickly roll back online code , Back to normal
14:20,review Code , Problems found in pre release verification
14:58, Modify the problem code to go online , Online recovery
The cause of the problem
BigDecimal Lost precision in amount calculation .
Cause analysis
First, let's use a piece of code to reproduce the root cause of the problem , As shown below :
public static void main(String[] args) {
BigDecimal bigDecimal=new BigDecimal(88);
System.out.println(bigDecimal);
bigDecimal=new BigDecimal("8.8");
System.out.println(bigDecimal);
bigDecimal=new BigDecimal(8.8);
System.out.println(bigDecimal);
}The results are as follows :

Found by test , When using double perhaps float These floating-point data types , Will lose precision ,String、int Will not be , Why is that ?
Let's open the constructor method to see the source code :
public static long doubleToLongBits(double value) {
long result = doubleToRawLongBits(value);
// Check for NaN based on values of bit fields, maximum
// exponent and nonzero significand.
if ( ((result & DoubleConsts.EXP_BIT_MASK) ==
DoubleConsts.EXP_BIT_MASK) &&
(result & DoubleConsts.SIGNIF_BIT_MASK) != 0L)
result = 0x7ff8000000000000L;
return result;
}The problem is doubleToRawLongBits In this way , stay jdk in double class (float And int Corresponding ) Provided in double And long transformation ,doubleToRawLongBits Will be double Convert to long, This method is the original method ( The bottom is not java Realization , yes c++ Realized ).
double The reason why something goes wrong , It's because the decimal point to binary lost precision .

BigDecimal Expand decimal number in processing N Times make it count on integers , And keep the corresponding precision information .
① float and double type , It is mainly designed for scientific calculation and engineering calculation , The reason for performing binary floating-point operations , It is designed to provide accurate and fast approximate sum calculation over a wide range of numerical values .
② It doesn't provide completely accurate results , So it should not be used for precise results .
③ When the floating-point number reaches a certain large number , Will automatically use scientific counting , Such a representation is only approximate to the real number but not equal to the real number .
④ When decimals are converted to binary, there will be infinite cycles or the length of the floating-point mantissa will be exceeded .
summary
therefore , In the process of precision calculation , We try to use String Type to convert .
We have created a high-quality technical exchange group , With good people , I will be excellent myself , hurriedly Click Add group , Enjoy growing up together . in addition , If you want to change jobs recently , Years ago, I spent 2 A wave of large factory classics were collected in a week , Those who are ready to change jobs after the festival can Click here to get !
Recommended reading
··································
Hello , I'm a procedural ape DD,10 Old driver developed in 、 Alibaba cloud MVP、 Tencent cloud TVP、 I have published books and started a business 、 State-owned enterprises 4 In the Internet 6 year . From ordinary developers to architects 、 Then to the partner . Come all the way , My deepest feeling is that I must keep learning and pay attention to the frontier . As long as you can hold on , Think more 、 Don't complain 、 Do it frequently , It's easy to overtake on a curve ! therefore , Don't ask me what I'm doing now, whether it's in time . If you are optimistic about one thing , It must be persistence to see hope , Instead of sticking to it when you see hope . believe me , Just stick to it , You must be better than now ! If you don't have any direction , You can pay attention to me first , Some cutting-edge information is often shared here , Help you accumulate the capital to overtake on the curve .
边栏推荐
- R language performs double sample t-test on multiple covariates based on lapply function, Welch double sample t-test analysis and double independent sample t-test on the mean of covariates correspondi
- Installation and configuration of NPM and yarn
- The decision tree model (based on the test data set) constructed by R language test is used for predictive reasoning, and the table function is used to calculate the confusion matrix. The accuracy of
- MySQL-进阶CRUD
- Clear table selection
- An analysis of DuPont analysis: the financial situation of East China Construction Group Co., Ltd
- The world's first financial chart database test benchmark project was approved, and ant group opened patent Co Construction
- Streaming media pressure measurement st load
- [STM32] transplantation of Hal library on 4-pin 0.96 inch OLED screen - hardware IIC (I)
- IDC发布《中国云原生市场分析》,蚂蚁集团已成覆盖最全面厂商之一
猜你喜欢

全球首个金融图数据库测试基准立项,蚂蚁集团开放专利共建

JS wechat games - fighting mosquitoes

Model Lightweight - cutting distillation Series yolov5 nonestructive Cutting (attached source)

Record the realization of animation effect on the page of small rocket of BiliBili (station B)

Idea cancels data simplification

英语太差怎么办,快来写一个“百词斩”软件给自己背单词

Api 接口优化的几个技巧

High jump wechat JS game source code
![[sans titre]](/img/a2/230bd1f4faa5a945bb495189b7ca3a.png)
[sans titre]

Top prize! The leading scientific and technological achievement "new technology" of 2022 digital Expo was awarded to oceanbase database
随机推荐
蚂蚁集团三项技术方案入选“2021年信息技术应用创新典型解决方案”
Talk about the importance of technology and tasks
蚂蚁集团加入低碳专利承诺,向全球无偿开放专利,促进节能减排
Warning: Accessing non-existent property ‘column‘ of module exports inside circular depen
MySQL advanced CRUD
Talking about thread pool with pictures and texts
Five best! Ant group passed the highest level evaluation of the "stability Assurance Plan" of the ICT Institute
Curator - implement service registration and discovery
General template for one page test plan of Agile Project
将对象数组转换成二维数组
R language performs double sample t-test on multiple covariates based on lapply function, Welch double sample t-test analysis and double independent sample t-test on the mean of covariates correspondi
Reconstruction of acquisition login component
【对话直播】图计算是下一个科技前沿
[introduction to software engineering] summary of knowledge points | suitable for examination review | easy to pass the exam
Convert an array of objects to a two-dimensional array
Power mathematics of leetcode326-3
Unable to enter the ArrayList underlying solution during debug
Best practice | zero basis implementation of applet voice input method
如何保障系统稳定性并实现减排?蚂蚁集团有这些关键技术
Recursive function Hanoi Tower