You should be able to provide a MathContext
instance with custom precision, e.g.
dividend.divide(divisor, new MathContext( 100 ) ); //whatever precision you need
题
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?
解决方案
You should be able to provide a MathContext
instance with custom precision, e.g.
dividend.divide(divisor, new MathContext( 100 ) ); //whatever precision you need
其他提示
You could set scale with appropriate rounding to achieve this
System.out.println(dividend.divide(divisor,49,BigDecimal.ROUND_HALF_UP));
I get the following output : 1.8734422753322275814153356813828056915434074561950
Apart from the solutions posted by others involving using a MathContext
there is always the possibility that a good Rational
class may be useful.
See here for a good one.
You should maintain your number as a Rational
to keep full accuracy and only render it into a decimal when saving it - at that point, of course, you will need to truncate again.
It is potentially possible to recover the inaccuracies - but not in a reliable way and it requires some maths. See here for my technique.