Sunday, August 12, 2018

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

In this Blog post, We are going to learn How to Convert BigInteger from/to  BigDecimal with examples.

BigInteger and BigDecimal examples

How to convert BigInteger to/from BigDecimal in java

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


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

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.

Related article


EmoticonEmoticon