15

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?

9
  • 2
    maybe you should read: stackoverflow.com/questions/35435691/… Commented Apr 3, 2017 at 11:19
  • What are ONE_HUNDRED and TEN? Commented Apr 3, 2017 at 11:25
  • TEN and ONE_HUNDRED does not exists as constants in BigDecimal Commented Apr 3, 2017 at 11:31
  • Define 'more ...'. Commented Apr 3, 2017 at 11:31
  • 1
    I faund solution. BigDecimal recovery = amount.divide(ONE_HUNDRED, 2, BigDecimal.ROUND_HALF_UP) But @ freedev - Why TEN and ONE_HUNDRED does not exists as constants in BigDecimal? I created constans myself Commented Apr 3, 2017 at 11:46

2 Answers 2

16
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(); } 
Sign up to request clarification or add additional context in comments.

1 Comment

3

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.

4 Comments

Intellij IDE is still saying: "'BigDecimal.divide()' called without a rounding mode argument more..." I don't think your answer answers the question
You know, TEN already exists as a constant in the BigDecimal class.
@RC right, I think this answer should fit the problem.
What exactly does IntelliJ say? what is the text after the more...part? Because you can use divide() without a rounding mode, and it is entirely safe if you use ONE_HUNDRED as argument.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.