美文网首页
Best practice for BigDecimal

Best practice for BigDecimal

作者: coolala | 来源:发表于2020-08-17 11:22 被阅读0次

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,因为除不尽

Useful reference

Basic example
format conversion example

相关文章

网友评论

      本文标题:Best practice for BigDecimal

      本文链接:https://www.haomeiwen.com/subject/dbvfjktx.html