Pay attention in Kotlin language for Double numbers calculations!


Even if you declare the variable as double, still pay attention for divisions

If you do not cast in every step (especially in division part) then unconsciously you might get wrong calculation

Example1:
var doubleNumber1: Double = 289.19 + (465 / 2)
Ø  521.19

What Kotlin gives is 521.19, what expected is 521.69. As you see in example1 even if you declare the variable name as double in division part it still make wrong calculation.

In division part, even if you cast to toDouble(), there is still wrong calculations.
Example2:
var doubleNumber2: Double = 289.19.toDouble() + (465 / 2).toDouble()
Ø  521.19

If you want to handle this wrong calculation, then casting should be inside of the parenthesis.
Example3:
var doubleNumber3: Double = 289.19.toDouble() + (465 / 2.toDouble())
Ø  521.69

Or you can write numbers with its precision part such as:
var doubleNumber4: Double = 289.19.toDouble() + 232.5
Ø  521.69


Another thing I have faced in Kotlin so far is Binary Floating Point (BFP) Exception. Which means there is a missing part in precision part while converting from binary to decimal in CPU based calculations!

For example;
0.1  + 0.2 = 0.30000000000000004441  

What expected is 0.3 but what returned is 0.30000000000000004441.
There is a standard called IEEE 754 standard.

Comments

Popular posts from this blog

Gove confirms mandatory housebuilding targets for councils will be abolished in face of Tory rebellion – UK politics live

Kotak Mahindra Bank Recruitment 2022 Released for Graduate Candidates And Apply Online