4

My question is very simple

In BigDecimal I want to do this:

public static void main (String [] args) {
    System.out.println(new BigDecimal(1).divide(new BigDecimal(3));
}

I want the result to be this : 0.333333333333333333333333333333333....... and not 0.3334 or 0.33.

Hoopje
  • 12,677
  • 8
  • 34
  • 50
zebiri djallil
  • 324
  • 2
  • 6
  • 17
  • 2
    You know there are an _infinite_ amount of 3's there? What is the precision you are looking for? – Tunaki Nov 24 '15 at 08:46
  • yeah , and i went the big number i can get – zebiri djallil Nov 24 '15 at 08:47
  • 1
    As big as what? As the memory allows you? Why do you want to store 1/3 to billions of billions of decimal? – Tunaki Nov 24 '15 at 08:48
  • 2
    Just append `...`, that's the biggest you can get :) – Maroun Nov 24 '15 at 08:50
  • 1
    The only way to represent this number exactly is with a fraction. If you use `double` or `BigDecimal` you can only approximate it. – Peter Lawrey Nov 24 '15 at 08:54
  • so i will scale it maybe by 100 ? – zebiri djallil Nov 24 '15 at 08:57
  • @zebiridjallil you can if you like but it is still an approximation. If you scale it to 15 digits and use rounding, you could just use a `double` and make your code much simpler `(1.0/3)` – Peter Lawrey Nov 24 '15 at 09:00
  • 1
    How many decimal places do you need? Just set the precision accordingly. – Henry Nov 24 '15 at 09:03
  • Maybe use rather [Fraction](http://commons.apache.org/proper/commons-math/userguide/fraction.html) instead of BigDecimal? – agad Nov 24 '15 at 09:08
  • @Henry implies that you can specify the decimal places to anything you want. This is incorrect. For example, scale = 4680 does not work. 4679 does. Don't ask why the limit is set to that; Looking at the source code of BigDecimal, I suspect that it is intrinsically set (does not seem to be extrinsic). – Tihamer Aug 06 '18 at 15:12

1 Answers1

19

All BigDecimal operations allow to set precision (number of digits after decimal point) and rounding mode.

System.out.println(
    new BigDecimal(1).divide(new BigDecimal(3), 10, RoundingMode.HALF_UP));

will output 0.3333333333. You can create a MathContext object to encapsulate this information. This is helpful since you typically need to do several operations with the same precision and rounding settings.

MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
System.out.println(new BigDecimal(1).divide(new BigDecimal(3), mc));
System.out.println(new BigDecimal(1).divide(new BigDecimal(9), mc));
Ha.
  • 3,454
  • 21
  • 24
  • 5
    I believe the "10" in `System.out.println(new BigDecimal(1).divide(new BigDecimal(3), 10, RoundingMode.HALF_UP));` means scale, which is the number of digits to the right of the decimal point. and the "10" in MathContext means precision, which is the number of significant digits. Source: https://stackoverflow.com/questions/3843440 Try to divide 20 by 3 and you will see the difference. – fall Feb 11 '21 at 05:20