当前位置:网站首页>What problems should be avoided when using BigDecimal type? (glory Collection Edition)
What problems should be avoided when using BigDecimal type? (glory Collection Edition)
2022-07-28 02:24:00 【Dragon back ride Shi】

Catalog
Preface
Hello everyone , I am procedural -- Handong , I'm here again !!
Java stay java.math Provided in the package API class BigDecimal, Used for more than 16 The number of significant bits of a bit is calculated precisely . Double precision floating point variables double Can handle 16 Bit significant number . in application , We need to calculate and process larger or smaller numbers .float and double It can only be used for scientific calculation or engineering calculation , Use... In Business Computing java.math.BigDecimal.BigDecimal What is created is an object , We can't use the traditional +、-、*、/ etc. Arithmetic operator Directly perform mathematical operations on its objects , You have to call its corresponding method . The parameter in the method must also be BigDecimal The object of . A constructor is a special method of a class , Specifically for creating objects , Especially objects with parameters .
When BigDecimal Improper use will cause serious consequences , I remember that I was still doing payment projects , The result is something wrong ,
But it's not a big problem , Procedure , Yes bag Normal , I'm not panicking at all .....

1、 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 .

2、 accident
Next, let's look at an accident at the cashier .
2.1. Problem description
The cashier reported an error in calculating the amount of goods , The order cannot be paid .
2.2. Accident level
P0 level

The heart is almost broken ........
2.3. 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
2.4. 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 .
This thing lost my performance for the whole month .......
about amount of money This sensitive field is better to be cautious ... Lesson from blood ....
Because computers use binary to process data , But a lot of decimals , Such as 0.1 The binary of is a wireless circular decimal , And this kind of number can't be accurately expressed in the computer .
BigDecimal It adopts a way of approximate value to express in the computer , So there are single precision floating-point numbers and double precision floating-point numbers .
BigDecimal As a single precision floating-point number float And double precision floating point numbers double, It's just an approximation when it comes to decimals , It's not true .
When using BigDecimal(Double) When you create one , Got BigDecimal It's a loss of precision .
And using a number that loses precision , The results are also imprecise .
Want to avoid this problem , Can pass BigDecimal(String) The way to create BigDecimal, In this case ,0.1 It will be expressed exactly .
It takes the form of a scale-free value 1, And a scale 1 The combination of .
You can see it here , Just click on it. Well .
边栏推荐
- Implementation of mongodb/mongotemplate.upsert batch inserting update data
- Under the new retail format, retail e-commerce RPA helps reshape growth
- OBS keyboard plug-in custom DIY
- feign调用get和post记录
- Aike AI frontier promotion (7.14)
- MySQL的pymysql操作
- Flex布局学习完成PC端
- CeresDAO:全球首个基于DAO赋能Web3.0的去中心化数字资产管理协议
- Clear the cause of floating and six methods (solve the problem that floating affects the parent element and the global)
- MySQL数据库InnoDB存储引擎中的锁机制(荣耀典藏版)
猜你喜欢

智能合约安全——selfdestruct攻击

都在说DevOps,你真正了解它吗?

Promise从入门到精通(第3章 自定义(手写)Promise)
![[advanced ROS] Lecture 9 robot model motion based on rviz and arbotix control](/img/7f/f0360210e8a9f7e45410d79635bfd9.png)
[advanced ROS] Lecture 9 robot model motion based on rviz and arbotix control

LeetCode 热题 HOT 100 -> 1.两数之和

MPLS tunnel experiment

Promise从入门到精通 (第2章 Promise的理解和使用)

探究flex-basis

Alipay applet authorization / obtaining user information

Codeforces Round #807 (Div. 2) A-C题解
随机推荐
Common problem types and methods of mathematical univariate differential proof problems in postgraduate entrance examination
Promise从入门到精通(第4章 async 和 await)
Likeshop takeout ordering system [100% open source, no encryption]
微信小程序图片根据屏幕比例缩放
【HCIP】BGP 特性
Codeforces Round #807 (Div. 2) A-C题解
MySQL create stored procedure ------ [hy000][1418] this function has none of deterministic, no SQL
Leetcode hot topic Hot 100 - > 2. Add two numbers
Common video resolution
[深入研究4G/5G/6G专题-42]: URLLC-14-《3GPP URLLC相关协议、规范、技术原理深度解读》-8-低延时技术-2-基于slot的调度与Slot内灵活的上下行符号配比
Promise from getting started to mastering (Chapter 3: customize (handwriting) promise)
Implementation of mongodb/mongotemplate.upsert batch inserting update data
Day6 函数和模块的使用
Zkrollup learning materials summary
Go learning 01
小米网站主页面大模块——小模块+导航(浮动案例)
小程序毕设作品之微信校园浴室预约小程序毕业设计成品(1)开发概要
SFTP file / folder upload server
Leetcode hot topic Hot 100 - > 1. Sum of two numbers
Clear the cause of floating and six methods (solve the problem that floating affects the parent element and the global)