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 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
using Kotlin BigDecimal
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..
With initial value
BigDecimal result = BigDecimal.ONE;
var result: BigDecimal
With initial value
var result: BigDecimal = BigDecimal.ONE
var result = BigDecimal.ONE
Ok so what about dynamic declaration is it not possible?. It’s possible let’s see how
BigDecimal result = new BigDecimal(int);
BigDecimal result = new BigDecimal(Double);
BigDecimal result = new BigDecimal(Long);
BigDecimal result = new BigDecimal(10);
var result: BigDecimal = BigDecimal.valueOf(Int)
var result: BigDecimal = BigDecimal.valueOf(Double)
var result: BigDecimal = BigDecimal.valueOf(Long)
var result: BigDecimal = BigDecimal.valueOf(10)
var num1: BigDecimal = BigDecimal.valueOf(10.4)
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.