Search code examples
javaprecisionbigdecimal

Dividing two number without losing precision


I am dividing two numbers 466489/249001 which results in Non-terminating decimal expansion.

As the BigDecimal class stores floating-point numbers with practically unlimited precision, I have gone for it.

    BigDecimal dividend = BigDecimal.valueOf(466489L);
    BigDecimal divisor  = BigDecimal.valueOf(249001L);
    System.out.println((double)466489/249001);
    //1.8734422753322275
    System.out.println(dividend.divide(divisor, MathContext.DECIMAL128));
    //1.873442275332227581415335681382806

From WolframAlpha I am getting the result as

1.87344227533222758141533568138280569154340745619495504034120344898213260187710089517712780269958755185722145694193999220...

So I suppose my result is precise.

Now I want to know how can I get more precision in my result using BigDecimal as calculated by WolframAlpha?


Solution

  • You should be able to provide a MathContext instance with custom precision, e.g.

    dividend.divide(divisor, new MathContext( 100 ) ); //whatever precision you need