[scala]How to make the BigDecimal is exact to integer part?

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)=>{
  multimes(c-1, begin)*(c+begin-1)

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

the number is the result of function mulCount.


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.

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 = ...

That said... Why not just use BigInt?

Need Your Help

Will using the JSContext from a UIWebview get my app rejcted?

javascript ios objective-c uiwebview webkit

We have a requirement in our app wherein we have to communicate across the web/native boundary - between JavaScript running in a UIWebView and ObjectiveC in the app.