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:
1 2 3 4 5 |
BigDecimal result; |
With initial value
1 2 3 4 5 |
BigDecimal result = BigDecimal.ONE; |
Kotlin:
1 2 3 4 5 |
var result: BigDecimal |
With initial value
1 2 3 4 5 |
var result: BigDecimal = BigDecimal.ONE |
or simply
1 2 3 4 5 |
var result = BigDecimal.ONE |
Default declarations:
- BigDecimal.ZERO
- BigDecimal.ONE
- BigDecimal.TEN
Ok so what about dynamic declration is it not possible?. It’s possible
java:
Syntax:
1 2 3 4 5 |
BigDecimal result = new BigDecimal(int); |
1 2 3 4 5 |
BigDecimal result = new BigDecimal(Double); |
1 2 3 4 5 |
BigDecimal result = new BigDecimal(Long); |
Declare as
1 2 3 4 5 |
BigDecimal result = new BigDecimal(10); |
Kotlin:
Syntax:
1 2 3 4 5 |
var result: BigDecimal = BigDecimal.valueOf(Int) |
1 2 3 4 5 |
var result: BigDecimal = BigDecimal.valueOf(Double) |
1 2 3 4 5 |
var result: BigDecimal = BigDecimal.valueOf(Long) |
Declare as
1 2 3 4 5 |
var result: BigDecimal = BigDecimal.valueOf(10) |
1 2 3 4 5 |
var num1: BigDecimal = BigDecimal.valueOf(10.4) |
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.