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) { this(val,MathContext.UNLIMITED); }
So, when creating an instance of BigDecimal, the argument should be enclosed in double quotation marks.
コメント