1

problem: When using BigDecimal for multiple calculations involving division. have a difficult to understand by decimals.

for example:

1/3*3

we expect is 1

but when you use BigDecimal.

we get ArithmeticException

if I add roundingMode for divide method .

we get 0.9999999999999

float result1 = 1f / 3f * 3f;
BigDecimal one = BigDecimal.valueOf(1);
BigDecimal three = BigDecimal.valueOf(3);
BigDecimal result2 = one.divide(three,64,BigDecimal.ROUND_HALF_UP).multiply(three);

System.out.println(result1);
System.out.println(result2);

The output

1.0
0.9999999999999999999999999999999999999999999999999999999999999999

I know this problem has something to do with rounding mode, but I don't know how to solve this problem

Thank you very much if you can help to propose a solution.

ps:My English is not good, I should be able to see, sorry :)

unreal
  • 11
  • 2
  • 1
    what's what you are wanting to solve? do you want to get always 1? why? The problem is not the class, but what is the purpose of the operation. Are you trying to represent money or e.g. physics calculations? or other types of operations (e.g. timestamps)? The solution depends on the usage that you will need for the resulting operations. โ€“ Victor Polo De Gyves Montero Mar 05 '21 at 04:41
  • The business is to split the discount amount of the order proportionally to the product The basic algorithm is Total discount: N Order amount: N Current product: MI Algorithm is Round (N/ M ยท Mi) We want the N/ M result to be as close to the expression itself as possible And of course as a programmer, I also want to understand what is the mechanism that makes the difference โ€“ unreal Mar 05 '21 at 09:38
  • This is a broad topic, but it seems you're dealing with money operations. A straight suggestion would be: Just use `long` to represent cents to operate your money values. This will represent that the minimum possible value is fixed to integer number of cents. So a value of like, 13250 cents (long) would be 132.50 dollars. This way you will avoid all discussion of BigDecimal and floating point operations. You will need to remember to your front-end that you're using cents to represent the units of your national currency, to fix your front-end accordingly. โ€“ Victor Polo De Gyves Montero Mar 06 '21 at 04:09

0 Answers0