Problem:

Have you felt calculations a bit confused any time or making multiple calculations changing your result / output.You may find this scenario in financial calculations like shopping where you add prices of different range.

In general we may get a weird output/result when you try to add up long precision numbers like a price of pen may be $4.9888888 which can be critical sometimes because of the long decimal values.

So there is a simple solution to handle these scenario’s by using a variable called BigDecimal.

 

BigDecimal:

BigDecimal makes your calculations very simpler and accurate when compared to double, by maintaining the precision.Let’s have a simple example like

You are representing a value as

–> 0.009999998

using BigDecimal

–> 0.01

 

Declaration:

How to use BigDecimal?. It’s is a bit different from your traditional style of declarations let see..

 

java:

 

With initial value

 

Kotlin:

 

With initial value

or simply

 

Default declarations:

  1. BigDecimal.ZERO
  2. BigDecimal.ONE
  3. BigDecimal.TEN

 

Ok so what about dynamic declration is it not possible?. It’s possible

 

 

java:

Syntax:
 

Declare as

 

Kotlin:

Syntax:
 

Declare as

 

More Info:

Isn’t it simpler but yes there do have some disadvantages of using this BigDecimal it’s a bit slower compared to double so use it only in financial calculations to get accurate result.

Also method overloading is not possible with the operators like add, sub, div, mul using BigDecimal so use it accordingly.

 

 

Show Buttons
Hide Buttons
Read previous post:
Creating a database and table MYSQL || PHP

Close