Home > Back-end >  Convert BigDecimal to BigInt Scala
Convert BigDecimal to BigInt Scala

Time:12-03

How to convert BigDecimal to BigInt in Scala?

I am trying to run the following code:

val x:BigDecimal = 2.335656787776;
    val y = new BigInt(x); 

The Error I get is:

Found:    (PlayGround.x : BigDecimal)
Required: java.math.BigInteger

Whereas when I do:

val x:BigDecimal = 2.335656787776;
val y = BigInt(x);   

I get:

None of the overloaded alternatives of method apply in object BigInt with types
 (x: java.math.BigInteger): BigInt
 (x: String, radix: Int): BigInt
 (x: String): BigInt
 (numbits: Int, rnd: scala.util.Random): BigInt
 (bitlength: Int, certainty: Int, rnd: scala.util.Random): BigInt
 (signum: Int, magnitude: Array[Byte]): BigInt
 (x: Array[Byte]): BigInt
 (l: Long): BigInt
 (i: Int): BigInt
match arguments ((PlayGround.x : BigDecimal))

How can I cast BigDecimal into BigInt?

CodePudding user response:

toBigInt does what you need. From docs

Converts this BigDecimal to a scala.BigInt.

Which does the following:

new BigInt(this.bigDecimal.toBigInteger)

There is also toBigIntExact which returns an option, if the conversion can be done losslessly.

CodePudding user response:

Use .toBigInt

val x: BigDecimal = 2.335656787776
x.toBigInt // returns 2

CodePudding user response:

A workAround that I found is:

val x:BigDecimal = 2.335656787776;
val y = BigInt("%.0f".format(x)); 

Is there any better way for the same?

  • Related