Early on, remember an interview, the interviewer asked what data type to store money with? I was only aware of 8 data types (Boolean, Byte, short, int, long, float, double, char), and I answered double because I thought double was the type of dual precision, but the interviewer told me I should use BIGDEC. imal! More information on this type of data is available recently in the payment project.
Chestnuts
Please read the question:
Example 1
Q, how much is the result? 0.01?
No! The result is 0.009999999999999998!
Why is that? Because both float and double are floating point numbers, both have a range of values and have a precision range. Floating-point numbers are different from commonly used decimals, and are often difficult to determine in use. The common problem is to define a floating-point number that, after a series of calculations, should be equal to a certain value, but it's not! The amount must be a fully accurate calculation, so double or float should not be used, but java.math.BigDecimal should be used.
Subtraction
How should the two BigDecimal values be subtraction? +,-, *,/So write? No!
Take a look at the example:
Example 2
Subtraction uses the English subtraction, namely Add, substract, multiply and divide
Size comparison
How to compare the size of two bigdecimal values? Can I use > or <? It's not possible!
Example 3
Two bigdecimal values are compared using the CompareTo method, the results are 1, 0, 1, respectively, less than, equal to, greater than; For 0, you can use Bigdecimal.zero to express!
Number of decimal digits and rounding rules
In the project, it involves the calculation of taxes, the results of the calculation may be more than 10 digits after the decimal point, then how to settle it? This requires rounding up the stuff.
Example 4
Where the first parameter of Setscale is the number of decimal places, the example is to keep 2 decimal places, followed by rounding rules.
MySQL Database design
BigDecimal in the storage, the database selects the decimal type, the length can be customized, such as 18; The decimal point we used in the project is 2, reserved 2 decimal places. Also note is the default value, must be written in 0.00, do not use the default NULL, otherwise in the addition and subtraction of the operation, will bring the conversion trouble!
' Balance ' decimal (18,2) DEFAULT ' 0.00 ' COMMENT ' account balance ',
Amount stored in Java