1

I am new to the Java world and am trying to learn how to use BigDecimal. What I am trying to do now is limit the number of decimal places in a division problem. My line of code is:

quotient=one.divide(x);

Where quotient, one and x are all of type BigDecimal. I cannot figure out, however, how to limit the number of decimal places to print out, saying that x is some large number, and one is equal to 1. All help is appreciated, thanks!

Sal
  • 1,471
  • 2
  • 15
  • 36

2 Answers2

1

That code will die a horrible death if the division has a non-terminating decimal expansion. See javadoc of divide(BigDecimal divisor):

if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.

Example:

BigDecimal one = BigDecimal.ONE;
BigDecimal x = BigDecimal.valueOf(7);
one.divide(x); // throws java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

Use one of the other overloads of divide(), e.g. divide(BigDecimal divisor, int scale, RoundingMode roundingMode):

BigDecimal one = BigDecimal.ONE;
BigDecimal x = BigDecimal.valueOf(7);
BigDecimal quotient = one.divide(x, 5, RoundingMode.HALF_UP);
System.out.println(quotient); // prints: 0.14286
BigDecimal one = BigDecimal.ONE;
BigDecimal x = BigDecimal.valueOf(7);
BigDecimal quotient = one.divide(x, 30, RoundingMode.HALF_UP);
System.out.println(quotient); // prints: 0.142857142857142857142857142857
Andreas
  • 154,647
  • 11
  • 152
  • 247
1

To set the number of decimal places in a variable BigDecimal you can use the following sentences depend that you want achieve

value = value.setScale(2, RoundingMode.CEILING) to do 'cut' the part after 2 decimals

or

value = value.setScale(2, RoundingMode.HALF_UP) to do common round

See Rounding BigDecimal to *always* have two decimal places

TomasMolina
  • 581
  • 5
  • 13