Sunday, August 12, 2018

How to convert BigInteger to BigDecimal or BigDecimal to BigInteger in Java with example

BigInteger and BigDecimal examples

Integer, Long and Double is basic numeric types which are used to store numeric values up to a limited range of values for basic arithmetic operations.BigInteger is used to store the large numeric values.BigDecimal is used to store the correct precision and rounding numbers where precision is important in financial applications.BigInteger and BigDecimal are classes in java.math package
Please have a look at previous posts of BigInteger tutorials

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);
BigInteger biginteger1 = new BigInteger("78459789");
BigDecimal bd1 = new BigDecimal(biginteger1,2);

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());
BigInteger bi1 = new BigInteger("78945612312312312312312");
BigDecimal bd1 = BigDecimal.valueOf(bi1.longValue());

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();
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.


Note: Only a member of this blog may post a comment.