Common usage of java in BigDecimal

2019-06-14 11:05:53

First, the accuracy problems

Second, subtraction, multiplication and division

Third, the size comparison

Fourth, the number of decimal places and rounding rules

Five, mysql database design

 

Accuracy problems:

Example 1

I ask, how much is the result? 0.01?

No! The result is .009999999999999998!

Why is this so? Because the float and double are floating-point numbers are in the range, has a range of precision floating-point number with decimal commonly used different use, it is often difficult to determine. A common problem is the definition of a floating point number after a series of calculations, it should have been equal to a determined value, but not really!

Amount must be perfectly accurate calculations, it can not use double or float, but should use java.math.BigDecimal.

Math:

Two BigDecimal values ​​How should it be Math +, -?, *, / So do not write?!

Addition, subtraction, multiplication and division using addition and subtraction in English, namely add, substract, multiply and divide

 

Size comparison:

BigDecimal value compared using two methods compareTo Comparative Results -1, 0, 1, respectively, less than, equal to, greater than one; for 0, can be represented using BigDecimal.ZERO!

 

Decimal places and rounding rules:

In the project, related to the calculation of taxes, the result of the calculation may be behind more than a dozen decimal point, then how to settle it? This requires rounding this stuff

The first parameter is the number of decimal places setScale, this example is 2 decimal places, followed by rounding rules.

 

mysql database design:

When BigDecimal during storage, database, select the decimal type, length can be customized, such as 18;. With the decimal point of our project is 2, 2 decimal places Note also that of the default, must be written 0.00, do not use the default the NULL, or during operations such as addition and subtraction sort, will bring trouble converting!

balance decimal (18,2) DEFAULT '0.00 ' COMMENT ' account balance',
---------------------
Author: is_Min
Source: CSDN
Original: https: // blog.csdn.net/qq_34581118/article/details/79799097
Disclaimer: This article is a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin www.cnblogs.com/wanfeng1937/p/11022363.html