0

I'm conducting an experiment in which we will occasionally have to divide small numbers by large numbers, for example: 4 / 90,000. Using a double results in a 4.444444444e. I was hoping perhaps a BigDecimal could handle this arithmetic and give me a meaningful decimal, but my implementation throws an error:

int count = 4;
int total = 90,000;
er = BigDecimal.valueOf(count).divide(BigDecimal.valueOf(total));

Error is:

Exception in thread "main" java.lang.ArithmeticException: Non-terminating   decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1616)

Update: I am interesting in atleast 3 decimal places of precision.

Talen Kylon
  • 1,858
  • 7
  • 30
  • 55

1 Answers1

0

You could pass a MathContext to the division method call. Something like,

int count = 4;
int total = 90000;
BigDecimal er = BigDecimal.valueOf(count).divide(BigDecimal.valueOf(total), 
        MathContext.DECIMAL128);
System.out.println(er);

And I get

0.00004444444444444444444444444444444444
Elliott Frisch
  • 191,680
  • 20
  • 149
  • 239