Original: http://blog.csdn.net/diyu122222/article/details/76887382
Decimal (18,0) 18 is the fixed-point precision, and 0 is the number of decimal digits.
Decimal (A, b) specifies the maximum number of decimal digits that can be stored to the left and right of the specified decimal point, with a maximum precision of 38.
b Specifies the maximum number of decimal digits that can be stored to the right of the decimal point. The number of decimal digits must be a value from 0 to a. The default number of decimal digits is 0.
Java provides the API class BigDecimal in the Java.math package to perform precise operations on the number of more than 16 significant bits. Double-precision floating-point variable double can handle a 16-bit valid number. In practical applications, larger or smaller numbers need to be calculated and processed. float and double can only be used for scientific calculations or engineering calculations, and Java.math.BigDecimal are used in commercial calculations. BigDecimal creates objects, we cannot use traditional + 、-、 *,/et arithmetic operators to perform mathematical operations on their objects directly, but must call their corresponding methods. The arguments in the method must also be BigDecimal objects. Constructors are special methods of classes that are designed to create objects, especially objects with parameters.
new BigDecimal("123");BigDecimal b = new BigDecimal("456");BigDecimal c = a.add(b);// 加BigDecimal d = a.subtract(b);// 减BigDecimal e = a.multiply(b);// 乘// 除,需指定精度, 保留6位小数,四舍五入,银行项目需注意,向上还是向下取整,不然钱会越算亏得越多BigDecimal f = a.divide(b, 6, BigDecimal.ROUND_HALF_UP));
Note: BigDecimal division, you need to specify the accuracy of the calculation answer, or the computer does not know your accuracy is how much, will throw an exception.
Exception in thread "main" java.lang.ArithmeticException
EG1:
new MathContext(2, RoundingMode.HALF_DOWN);//精度为2,舍入模式为大于0.5进1,否则舍弃。 BigDecimal a = new BigDecimal(0.5);BigDecimal b = new BigDecimal(0.2);System.out.println(a.divide(b,mc));
- Bigdecimal.signum () returns the Sign function for this BigDecimal.
This method returns -1,0, or 1, and the value of the corresponding BigDecimal is categorized as negative, 0, or positive.
- BigDecimal Comparison Size
new BigDecimal(0.5);BigDecimal b = new BigDecimal(0.2);int c = a.compareTo(b);//结果C 是:-1 小于,0 等于,1 大于
Java's BigDecimal