# [JAVA] About the treatment of BigDecimal (with reflection)

I think there are many situations where java is used in development work. I think that Big Decimal may be used when building calculation logic. Suddenly, it's a different type from a normal integer, so I was confused, so I decided to leave it in the article.

## What is Big Decimal

https://docs.oracle.com/javase/jp/8/docs/api/java/math/BigDecimal.html> From oracle.docs No, I don't really understand even if it is said mathematically. .. .. So, in other words ... In the case of calculations where floats and doubles cause errors, unintended results may be obtained. For example

#### `double.java`

``````
double result = 10d / 6d;
System.out.println(result)
//Output 1.6666666666666666666666666666666666666666
``````

It's like that. As you may know, if you want to calculate "bank rounding", the above example is too irregular and you will be in trouble. That's where Big Decimal comes in. It is often used for so-called core banking calculations.

• Bank rounding When rounding with N digits If the Nth digit is even, round down 5 or less. Round up otherwise. If the Nth digit is odd, truncate less than 5. Round up otherwise. It is called.

BigDecimal is different from the normal number calculation and calculates as follows.

#### `BigDecimalCalc.java`

``````
//When dividing 1000 of BigDecimal type by 100 of int type
BigDecimal bigNum = BigDecimal.valueOf(1000);
BigDecimal result = bigNum.divide(BigDecimal.valueOf(100), 2, RoundingMode.DOWN);
System.out.println(result);

``````

Use a special method for divide. Normal / cannot be used. See oracle.docs for details.

## When comparing with 0

How to handle 0 of BigDecimal in conditional branching etc. I'm addicted to this if I'm not used to it. Of course I was addicted to it because I am also a beginner.

#### `ZeroCompare.java`

``````
if(Value to compare.compareTo(BigDecimal.ZERO) == 0) {
//・ ・ ・
}

``````

It looks like. In other words, there is no difference compared to 0, so 0! It will be a comparison. By the way, if it is 0 or more or 0 or less

#### `Compare.java`

``````
ZeroCompare.java
if(Value to compare.compareTo(BigDecimal.ZERO) > 0) {
//・ ・ ・
}
``````

To do.

## Summary

BigDecimal is used differently than primitive types. It is necessary to be aware of that. Especially for java beginners like me, it's hard to accidentally use floats and doubles when you have to make accurate calculations in actual development work, or to use BigDecimal incorrectly and cause compilation errors. Don't do it. You may not usually care about it, but in the case of work, I would like to listen carefully to the purpose of the calculation logic to be developed and the required accuracy before developing it. [Reflection]