Create BigDecimal from unscaled long

Viewed 150

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?

3 Answers

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).

new BigDecimal( 1099L )
.movePointLeft(2)

Use constructor taking only a long, without the MathContext.

See this code run live at IdeOne.com.

Related