Problem:
Have you felt calculations a bit confused any time or making multiple calculations changing your result / output.You may find this scenario mostly in financial calculations like shopping where you can 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 in kotlin.
So there is a simple solution to handle these scenario’s by using a variable called Kotlin BigDecimal. This can support long precision and can also easily converted from double, float, int numbers…
Kotlin Bigdecimal:
Kotlin 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 stated below
–> 0.009999998
using Kotlin BigDecimal
–> 0.01
Declaration:
How to use kotlin bigdecimal ?. It’s is a bit different from your traditional style of declarations let see in both java and Kotlin scenarios..
java:
BigDecimal result;
With initial value
BigDecimal result = BigDecimal.ONE;
Kotlin:
var result: BigDecimal
With initial value
var result: BigDecimal = BigDecimal.ONE
or simply
var result = BigDecimal.ONE
Default declarations:
- BigDecimal.ZERO
- BigDecimal.ONE
- BigDecimal.TEN
Ok so what about dynamic declaration is it not possible?. It’s possible let’s see how
java:
Syntax:
BigDecimal result = new BigDecimal(int);
BigDecimal result = new BigDecimal(Double);
BigDecimal result = new BigDecimal(Long);
Declare as
BigDecimal result = new BigDecimal(10);
Kotlin:
Syntax:
var result: BigDecimal = BigDecimal.valueOf(Int)
var result: BigDecimal = BigDecimal.valueOf(Double)
var result: BigDecimal = BigDecimal.valueOf(Long)
Declare as
var result: BigDecimal = BigDecimal.valueOf(10)
var num1: BigDecimal = BigDecimal.valueOf(10.4)
More Info:
Isn’t it simpler but yes there do have some disadvantages of using this Kotlin 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 based on your requirement.
If you have any query in this tutorial on kotlin bigdecimal do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates.