What is BigDecimal
Immutable, arbitrary-precision signed decimal numbers.
Why use it
The two java primitive types(double and float) are floating point numbers, which is stored as a binary representation of a fraction and an exponent.
Unlike fixed point numbers, floating point numbers will most of the times return an answer with a small error (around 1E-19).
A BigDecimal is an exact way of representing numbers.
When dealing with money, or precision is a must, use BigDecimal. Otherwise Doubles tend to be good enough.
Pros and cons
Pros: precise
Cons: slower, cannot use +, -, *, / directly.
Example
BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("0.9");
BigDecimal c = new BigDecimal("0.8");
BigDecimal x = a.subtract(b);
BigDecimal y = b.subtract(c);
// don't use equals(), it requires value and scale should be equal.
// if use equal(), 1.2 doesn't equal to 1.20.
if(x.compareTo(y)){
// do something
}
Good practices, use string representation.
BigDecimal BigDecimal(String s); // case 1
static BigDecimal valueOf(double d); // case 2, using the double's canonical string representation provided by the Double.toString(double) method.
Bad cases, lose precision.
BigDecimal(double val) // case 1
Special case, be careful about divide
BigDecimal d1 = new BigDecimal("123.456");
BigDecimal d2 = new BigDecimal("23.456789");
BigDecimal d3 = d1.divide(d2, 10, RoundingMode.HALF_UP); // 保留10位小数并四舍五入
BigDecimal d4 = d1.divide(d2); // 报错:ArithmeticException,因为除不尽
网友评论