Skip to content
Advertisement

Create BigDecimal from unscaled long

I’m trying to convert long 1099 to BigDecimal 10.99; This gives me 11.00:

long cost = 1099;
MathContext CENTS = new MathContext(2,RoundingMode.HALF_EVEN);
BigDecimal result = (new BigDecimal(cost,CENTS)).movePointLeft(2);

AFAIK this should work. What’s my bonehead error?

Advertisement

Answer

The error is that there’s a distinction between scale and precision. The constructor of MathContext accepts a precision, which is a total number of decimal digits on either side of the decimal point. (For example, the original BigDecimal you had was essentially 11 * 10^2, as if it were in scientific notation.)

Change it to new MathContext(4, RoundingMode.HALF_EVEN).

Advertisement