当前位置:网站首页>Correct use of BigDecimal
Correct use of BigDecimal
2022-07-07 01:55:00 【Dily_ Su】
List of articles
One 、 background
BigDecimal Usually it is mainly used to calculate money , It provides many construction methods by itself , However, the improper use of these construction methods will cause the loss of accuracy , Thus causing accidents .
Two 、 Accident cases
1、 problem
The cashier calculated the commodity price and reported an error , The order cannot be paid
2、 Problem recurrence
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);
}
3、 Source code analysis
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 ).
4、 Cause analysis
stay java in BigDecimal Expand the decimal number when processing data 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 .
3、 ... and 、 summary
When the design reaches the accuracy calculation , We try to use String Type to convert , And it's about BigDecimal The calculation of , Use its corresponding method to calculate .
Four 、 Tool class
Here's a package BigDecimal Tool class
public class BigDecimalUtils {
/** * double Add * * @param v1 Addition number * @param v2 Addition number * @return and */
public static BigDecimal doubleAdd(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2);
}
/** * float Add * * @param v1 Addition number * @param v2 Addition number * @return and */
public static BigDecimal floatAdd(float v1, float v2) {
BigDecimal b1 = new BigDecimal(Float.toString(v1));
BigDecimal b2 = new BigDecimal(Float.toString(v2));
return b1.add(b2);
}
/** * double reduce * * @param v1 minuend * @param v2 Subtract * @return Bad */
public static BigDecimal doubleSub(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2);
}
/** * float reduce * * @param v1 minuend * @param v2 Subtract * @return Bad */
public static BigDecimal floatSub(float v1, float v2) {
BigDecimal b1 = new BigDecimal(Float.toString(v1));
BigDecimal b2 = new BigDecimal(Float.toString(v2));
return b1.subtract(b2);
}
/** * double ride * * @param v1 Factor * @param v2 Factor * @return product */
public static BigDecimal doubleMul(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2);
}
/** * float ride * * @param v1 Factor * @param v2 Factor * @return product */
public static BigDecimal floatMul(float v1, float v2) {
BigDecimal b1 = new BigDecimal(Float.toString(v1));
BigDecimal b2 = new BigDecimal(Float.toString(v2));
return b1.multiply(b2);
}
/** * double except * * @param v1 Divisor * @param v2 Divisor * @return merchant */
public static BigDecimal doubleDiv(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
// Keep two decimal places ROUND_HALF_UP = rounding
return b1.divide(b2, 2, RoundingMode.HALF_UP);
}
/** * float except * * @param v1 Divisor * @param v2 Divisor * @return merchant */
public static BigDecimal floatDiv(float v1, float v2) {
BigDecimal b1 = new BigDecimal(Float.toString(v1));
BigDecimal b2 = new BigDecimal(Float.toString(v2));
// Keep two decimal places ROUND_HALF_UP = rounding
return b1.divide(b2, 2, RoundingMode.HALF_UP);
}
/** * double<br> * Compare v1 v2 size * * @param v1 * @param v2 * @return v1>v2 return 1 v1=v2 return 0 v1<v2 return -1 */
public static int doubleCompareTo(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.compareTo(b2);
}
/** * float<br> * Compare v1 v2 size * * @param v1 * @param v2 * @return v1>v2 return 1 v1=v2 return 0 v1<v2 return -1 */
public static int floatCompareTo(float v1, float v2) {
BigDecimal b1 = new BigDecimal(Float.toString(v1));
BigDecimal b2 = new BigDecimal(Float.toString(v2));
return b1.compareTo(b2);
}
}
边栏推荐
- AcWing 361. Sightseeing cow problem solution (SPFA seeking positive ring)
- ROS学习(21)机器人SLAM功能包——orbslam的安装与测试
- AcWing 1148. Secret milk transportation problem solution (minimum spanning tree)
- ROS learning (24) plugin
- 对C语言数组的再认识
- 微服务架构介绍
- Long press the button to execute the function
- ROS学习(26)动态参数配置
- 设置Wordpress伪静态连接(无宝塔)
- WCF Foundation
猜你喜欢
centos8安装mysql报错:The GPG keys listed for the “MySQL 8.0 Community Server“ repository are already ins
New job insights ~ leave the old and welcome the new~
sql中批量删除数据---实体中的集合
Batch delete data in SQL - set in entity
2022/0524/bookstrap
ROS学习(25)rviz plugin插件
Clickhouse fields are grouped and aggregated, and SQL is queried according to the granularity of any time period
ROS学习(24)plugin插件
Analyze "C language" [advanced] paid knowledge [II]
Instructions for using the domain analysis tool bloodhound
随机推荐
MySQL最基本的SELECT(查询)语句
Appium automation test foundation uiautomatorviewer positioning tool
swiper组件中使用video导致全屏错位
微服务架构介绍
C language instance_ five
AcWing 344. Solution to the problem of sightseeing tour (Floyd finding the minimum ring of undirected graph)
First experience of JSON learning - the third-party jar package realizes bean, list and map to create JSON format
How did partydao turn a tweet into a $200million product Dao in one year
JS how to quickly create an array with length n
Baidu flying general BMN timing action positioning framework | data preparation and training guide (Part 2)
爬虫实战(六):爬笔趣阁小说
BigDecimal 的正确使用方式
Get to know MySQL for the first time
Use nodejs to determine which projects are packaged + released
LeetCode. 剑指offer 62. 圆圈中最后剩下的数
AcWing 1140. Shortest network (minimum spanning tree)
[unique] what is the [chain storage structure]?
POJ 3177 Redundant Paths POJ 3352 Road Construction(双连接)
AcWing 344. 观光之旅题解(floyd求无向图的最小环问题)
新工作感悟~辞旧迎新~