2

I want to calculate the of a number I receive in BigDecimal format :

BigDecimal number1 = new BigDecimal("17");
int percentage = 50;
BigDecimal percentageAmount = number1.multiply(new BigDecimal(percentage/100));

but I got a 0 !

en Lopes
  • 1,863
  • 11
  • 48
  • 90
  • Solution 1: `number1.multiply(BigDecimal.valueOf(percentage/100.0))` --- Solution 2: `number1.multiply(BigDecimal.valueOf(percentage)).divide(BigDecimal.valueOf(100))` – Andreas Sep 25 '18 at 05:51
  • To elucidate: the problem is that 50 is an integer, and 100 is an integer. So when it gets to 50/100 it doesn't magically change the result into a fraction (floating point number), it does integer maths on it, and integer maths doesn't have any fractions. – Rick Sep 25 '18 at 06:09

1 Answers1

2

Cast the divided result to double. The integer division is returning zero as expected. This should work.

BigDecimal percentageAmount = number1.multiply(new BigDecimal((double)percentage/100));

Or, make the 100 to 100.0.

BigDecimal percentageAmount = number1.multiply(new BigDecimal(percentage/100.0));

These solutions would work if the number is small as you have used. But these solutions won't give the precise results when the number is big. This would be the best approach for avoiding the precision error:

BigDecimal percentageAmount = number1.multiply(BigDecimal.valueOf((double)percentage/100));
Shahid
  • 2,288
  • 1
  • 14
  • 24