3

I have a very strange problem in my Kotlin app :

14.9 - 12.8 == 2.0999994

I also tried to do :

var1 = 14.9
var2 = 12.8
var1.minus(var2)

but I strangely get the same result.

How can I subtract 2 floats in Kotlin and getting a decent value, like 2.1 in this case ?

Milind Mevada
  • 3,145
  • 1
  • 14
  • 22
Mathieu
  • 1,435
  • 3
  • 16
  • 35

1 Answers1

0

This is a floating point error if you are not into financial calculations then you can use

var var1 = 14.9
var var2 = 12.8
var var3 = var1.minus(var2)
println("%.2f".format(var3))

Else try BigDecimal

Dev
  • 6,628
  • 2
  • 25
  • 34
  • Unfortunatly I don't want to just print or display the result, I also need to do some calculations with it. But I am going to try the BigDecimal thing, thanks for the tip ! – Mathieu Aug 21 '18 at 09:35