I was writing a code that handles decimal numbers, and I got into it in various ways, so a memo at that time.

I needed to divide a decimal value, so I wrote the code to divide using BigDecimal as follows.

```
public class Divide {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal(1.1);
BigDecimal num2 = new BigDecimal(100);
System.out.println(num1.divide(num2));
}
}
```

Since it is 1.1 ÷ 100, the result should be 0.011, but when I execute it, it outputs "0.01100000000000000088817841970012523233890533447265625". I wondered why, but it wasn't used properly.

I took 1.1 as an argument when generating BigDecimal, but it seems that this one already contains an error. Since decimal decimals are represented by binary decimals, there are some values that cannot be represented in the first place. If you think about it, it's natural. .. .. Since 1.1 is a value that cannot be expressed, if BigDecimal is generated based on it, the error will be retained.

Avoid using double and float values as shown below.

```
public class Divide {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("1.1");
BigDecimal num2 = new BigDecimal("100");
System.out.println(num1.divide(num2));
}
}
```

This will give you an accurate calculation. Then, does BigDecimal need a constructor that takes a double as an argument?

ArithmeticException occurs when calculating an indivisible value as shown below.

```
public class Divide {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("1.1");
BigDecimal num2 = new BigDecimal("3");
System.out.println(num1.divide(num2));
}
}
```

BigDecimal's divide method seems to raise an exception if it is not divisible by default. Therefore, specify the number of digits and the rounding method as shown below.

```
public class Divide {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("1.1");
BigDecimal num2 = new BigDecimal("3");
System.out.println(num1.divide(num2,2,RoundingMode.FLOOR));
}
}
```

Recommended Posts