In this Blog post, We are going to learn

*How to Convert BigInteger from/to BigDecimal with examples*.#### BigInteger and BigDecimal examples

*BigInteger*and

*BigDecimal*are classes in java.math package

You can also check my previous posts on BigInteger class in java.

- BigInteger tutorials with examples
- BigInteger to Integer or Integer to BigInteger example
- BigInteger to String example
- BigDecimal to String or String to BigDecimal example

### How to convert BigInteger to BigDecimal in java?

There are two ways we can convert from BigInteger to BigDecimal.

#### Using BigDecimal constructor

BigDecimal has one constructor with accepting the BigInteger value and returns bigDecimal value BigDecimal(BigInteger unscaled value) with zero scale BigDecimal(BigInteger unscaled value, int scaledValue) convert to bigdeimal with scaled value is applied NumberFormatException throws if given scale is negative```
BigInteger biginteger = new BigInteger("4785961234");
BigDecimal bd = new BigDecimal(biginteger);
System.out.println(bd);
BigInteger biginteger1 = new BigInteger("78459789");
BigDecimal bd1 = new BigDecimal(biginteger1,2);
System.out.println(bd1);
```

outputs```
4785961234
784597.89
```

#### Using BigDecimal.valueOf method

This will convert to BigDecimal. The only limitation with this, if bigintger contains a larger number as shown in below, It will give the wrong number as intValue used you can use intValue or longValue of BigInteger in valueOf method```
BigInteger bi = new BigInteger("789456");
BigDecimal bd = BigDecimal.valueOf(bi.longValue());
System.out.println(bd);
BigInteger bi1 = new BigInteger("78945612312312312312312");
BigDecimal bd1 = BigDecimal.valueOf(bi1.longValue());
System.out.println(bd1);
```

outputs```
789456
-6452323164568604168
```

### How to Convert BigDecimal to BigInteger in java?

when we converted*BigDecimal to BigInteger*, bigdecimal precision will be discarded and returns the double/long value in the Biginteger form using toBigInteger() method BigDecimal provides toBigInteger() method - this converts to BigInteger

```
BigDecimal bigDecimal = new BigDecimal("457695216.89566");
BigInteger bigInteger=bigDecimal.toBigInteger();
System.out.println(bigInteger);
```

Hope you understand the conversion of Biginteger and BIgDecimalin java. Please like or leave a comment in facebook/twitter and subscribe to email for our latest blog posts.
EmoticonEmoticon