简体   繁体   中英

Trying to limit number of decimal places for BigDecimal division Java

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!

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() , eg 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM