How to convert BigDecimal type to int type in Java

How to convert BigDecimal type to int type in Java

To convert a BigDecimal type to an int type in Java, use the intValue method.

BigDecimal bd = new BigDecimal("10");
int i = bd.intValue();

Conversely, to convert an int type to a BigDecimal type, use the valueOf method.

int i = 10;
BigDecimal bd = BigDecimal.valueOf(i);

Instead of new BigDecimal, valueOf is recommended, since it is cached in valueOf and is not always instantiated.

In contrast, new BigDecimal is always instantiated. It’s a small detail, but you have to be memory conscious in Java.

Accounting uses BigDecimal type

In accounting systems, BigDecimal is usually used.

However, BigDecimal may also become a circular decimal number, depending on how the instance is created.

Let’s try to divide by passing a double type to the constructor.

BigDecimal bd1 = new BigDecimal(1058.1);
BigDecimal bd2 = new BigDecimal(10);
System.out.println(bd1.divide(bd2)); // 105.809999999999990905052982270717620849609375

This is because the following is provided in the constructor of BigDecimal.

public BigDecimal(double val) {

So, when creating an instance of BigDecimal, the argument should be enclosed in double quotation marks.


Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL