当前位置:网站首页>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 .
边栏推荐
- The level "trap" of test / development programmers is not a measure of one-dimensional ability
- Flex布局学习完成PC端
- How to evaluate the effectiveness of R & D personnel? Software Engineer reports help you see everyone's contribution
- Plato Farm在Elephant Swap上铸造的ePLATO是什么?
- Likeshop takeout ordering system [100% open source, no encryption]
- How to put app on the app store?
- Four common post data submission methods
- C#引入WINAPI传递中文字符串参数字符集问题
- Common video resolution
- Appium 点击操作梳理
猜你喜欢

Understand the "next big trend" in the encryption industry - ventures Dao

go 学习02 基础知识

小米网站主页面大模块——小模块+导航(浮动案例)

In it, there is a million talent gap, and the salary rises, but it is not capped

regular expression

Flex开发网页实例web端

A lock faster than read-write lock. Don't get to know it quickly

11-Django-基础篇-数据库操作

They are all talking about Devops. Do you really understand it?

How to evaluate the effectiveness of R & D personnel? Software Engineer reports help you see everyone's contribution
随机推荐
The cooperation between starfish OS and metabell is just the beginning
软考 --- 数据库(2)关系模型
SFTP file / folder upload server
上课笔记(5)(1)——#593. 二分查找(binary)
[Star Project] small hat aircraft War (V)
Behind every piece of information you collect, you can't live without TA
Go learn 02 basic knowledge
Flex开发网页实例web端
了解加密行业的“下一个大趋势”——Ventures DAO
Under the new retail format, retail e-commerce RPA helps reshape growth
Alipay applet authorization / obtaining user information
MySQL是如何利用索引的(荣耀典藏版)
小程序毕设作品之微信校园浴室预约小程序毕业设计成品(1)开发概要
清除浮动的原因和六种方法(解决浮动飞起影响父元素和全局的问题)
Promise from introduction to mastery (Chapter 2 understanding and use of promise)
Uniapp summary (applet)
「冒死上传」Proe/Creo产品结构设计-止口与扣位
[Yugong series] use of tabby integrated terminal in July 2022
Leetcode hot topic Hot 100 - > 1. Sum of two numbers
探究flex-basis