Question

On scala my BigDecimal is 3.721443204405954385563870541379242E+54 I would like to result to 3721443204405954385563870541379246659709506697378694300

My result is: 3.114968783111033211375362915188093E+41 I would like to result to be: 311496878311103321137536291518809134027240

I do not know the scale and the result should be only show the integer part.

val multimes:(Int, Int)=>BigDecimal=(c:Int, begin:Int)=>{
if(c==1)
  BigDecimal.apply(begin)
else
  multimes(c-1, begin)*(c+begin-1)
}

def mulCount(c:Int):BigDecimal={
val upper=multimes(c,c+1)
val down=multimes(c,2)
upper/down
}

the number is the result of function mulCount.

Was it helpful?

Solution

The BigDecimal class has a number of nonintuitive behaviors in Scala 2.10. This will get better in 2.11, but I can't quite tell from your example whether it will fix what you want. Probably not; Scala has a default MathContext which keeps about 128 bits of information (~34 decimal digits), and I think that's what you're running into here.

If you don't have a decimal problem--and here you don't--then the easiest thing to do is just use BigInt instead. It will scale to however many digits you actually need.

If you must express this as a decimal problem, you should explicitly supply a MathContext that has enough digits:

if (c==1) BigDecimal.apply(begin, new java.math.MathContext(60))

and that MathContext will, if always used on the left-hand side of operations, propagate through to your result.

OTHER TIPS

It sounds as though you're mostly concerned about the appearance of the number, and don't want to see it in scientific notation with the exponent.

This is default behaviour for just printing a BigDecimal and can't be overridden. But you can explicitly convert it to a String before printing.

This should do the trick:

val bd: BigDecimal = ...
println(bd.bigDecimal.toPlainString)

That said... Why not just use BigInt?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top