Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigDecimal divide with scale

I have

private static final BigDecimal ONE_HUNDRED = new BigDecimal(100);
    private static final BigDecimal TEN = new BigDecimal(10);

BigDecimal decimal = new BigDecimal(1050); I need to get 10% I write BigDecimal decimalResult = decimal.divide(ONE_HUNDRED).multiply(TEN)//100, 10

But Intellij IDE says:

'BigDecimal.divide()' called without a rounding mode argument more...

I added BigDecimal.ROUND_HALF_UP and all others but I get wrong result. I need 1050/100 = 10.5 but if I add BigDecimal.ROUND_HALF_UP result = 11.

How can I correctly divide with scale parameters?

like image 259
user5620472 Avatar asked Apr 03 '17 11:04

user5620472


People also ask

How do you divide in BigDecimal?

divide(BigDecimal divisor) scale() – divisor. scale()). Parameters: This method accepts a parameter divisor by which this BigDecimal is to be divided for obtaining quotient. Return value: This method returns a BigDecimal which holds the result (this / divisor).

How do you scale BigDecimal?

scale() is an inbuilt method in java that returns the scale of this BigDecimal. For zero or positive value, the scale is the number of digits to the right of the decimal point. For negative value, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.

How do you divide decimals in Java?

To divide two decimal numbers (or an integer by a decimal or vice-versa), you can use simple double division to ensure a decimal result. When working with larger numbers or numbers that needs to be extremely precise, you can use the BigDecimal Java class instead of floating point arithmetic.


2 Answers

public static double divide(double d1, double d2) {
    BigDecimal b1 = new BigDecimal(d1);
    BigDecimal b2 = new BigDecimal(d2);
    return b1.divide(b2, 2, RoundingMode.DOWN).doubleValue();
}
like image 162
panqingcui Avatar answered Oct 21 '22 04:10

panqingcui


This example returns 105.0000

public class TestBigDecimal {
  static BigDecimal decimal = new BigDecimal(1050).setScale(4, BigDecimal.ROUND_HALF_UP);
  static BigDecimal ONE_HUNDRED = new BigDecimal(100);
  static BigDecimal TEN = new BigDecimal(10);

  public static void main(String[] args)
  {
    BigDecimal decimalResult = decimal.divide(ONE_HUNDRED).multiply(TEN) ;
    System.out.println(decimalResult);
  }
}

You should adjust the scale during the creation of decimal variable.

like image 45
freedev Avatar answered Oct 21 '22 03:10

freedev