Search code examples
scalabigdecimaldigitspidecimal

Scala BigDecimal how to display more decimals?


First of all, I am aware that there is a similar topic regarding the division of 1 by 3. However, my code is quite different and I don't know how to apply the information given there to my situation. I would appreciate any and all help.

I made a Pi calculator in Scala and at the end of the code I print the result. However, I want to have a much larger number of decimals and I don't know how to achieve that. My current output is :

Expected decimals: 34
3.141592653589793238462643383279500

Here's the code:

package theBrain
object Calculator 
{
def main(args: Array[String]) 
{

var i = 100
var j = 100
var lastValueOnFirstLine = j+i
var array = new Array [BigDecimal] (0)

var counter = i-1

for (d <- j to lastValueOnFirstLine by 1)
{
  var almostPi = BigDecimal(0)
  var pi = BigDecimal(0)

  for (b <- 0 to d by 1)
  {
      var partialAnswer = (if (b%2 != 0) {-1} else {1} )/((BigDecimal(2)*BigDecimal(b))+BigDecimal(1))
      almostPi = partialAnswer + almostPi

  }
  pi = 4*almostPi
 array = array:+pi
}

for (z <- counter to 0 by -1){
var array2 = new Array [BigDecimal] (0)
var length = array.length -2
for (a <- 0 to length by 1){

var result = (array(a)+array(a+1))/2
array2 = array2:+result
}
array = array2
counter -= 1
}

for (element <- array) {
println("Expected decimals: " + element.precision)
println(element)
}

}
}

Solution

  • You have to supply a different java.math.MathContext when you create your instances of BigDecimal. Note that this effects the precision of the calculation, not only how many decimals are printed on output. This is quite different from the mere formatting of numbers.

    scala> BigDecimal(1) / 3
    res0: scala.math.BigDecimal = 0.3333333333333333333333333333333333
    
    scala> res0.precision
    res1: Int = 34
    
    scala> BigDecimal(1, new java.math.MathContext(50)) / 3
    res2: scala.math.BigDecimal = 0.33333333333333333333333333333333333333333333333333
    
    scala> res2.precision
    res3: Int = 50