-1

I have

    BigDecimal a = new BigDecimal(7);
    BigDecimal b = new BigDecimal(13);
    BigDecimal c = new BigDecimal(26);
    System.out.print((a.divide(b)).multiply(c));

this code generates an exception:

java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

It means that I need to set RoundingMode.

But I need to get result only without loss of precision.

How can I achieve it?

Lii
  • 11,553
  • 8
  • 64
  • 88
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • 7
    Seems like you want to work with fractions, not with decimals. You could look around for a library with a Fraction class, or write your own. – Dawood ibn Kareem Feb 05 '16 at 10:57
  • Check this out: http://commons.apache.org/proper/commons-math/userguide/fraction.html There's also a discussion here: http://stackoverflow.com/questions/474535/best-way-to-represent-a-fraction-in-java – mohammedkhan Feb 05 '16 at 11:20
  • @David Wallace thanks - you are right – gstackoverflow Feb 05 '16 at 11:31

4 Answers4

1

Seeing as 7/13 goes on to infinity what you're asking for is not possible. Your only possible option is to have a large precision when you divide.

mohammedkhan
  • 953
  • 6
  • 14
0

Dividing 7 by 13 will giving you long and non terminating decimal(0.53846153846.....). So you need to set the precision limit to it. Try this:

a.divide(b, x, RoundingMode.HALF_UP).multiply(c)

where x is the precision limit you want to set.

The Javadocs says:

When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.)

As a corollary of computing the exact result, the rounding mode setting of a MathContext object with a precision setting of 0 is not used and thus irrelevant. In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 2
    That will solve the exception, but the questioner needs the number to a high precision, this defeats the objective. – mohammedkhan Feb 05 '16 at 10:59
0

Decimal places of 7/3 is going to infinity. You must round it AFAIK. You can keep 6 decimal places because first 6 places repeats infinitely

http://m.wolframalpha.com/input/?i=7%2F13

Hyperion
  • 382
  • 8
  • 16
0

Apache commons library can it

Fractions

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710