Subscribe to this blog

Newsletter

Search This Blog

Pages

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!