0

I'm performing very basic maths operations.

fun main() {
    
    val factor:Double = 0.0351951
    var num1:Double = 250.0
    
    //prints 250.0 as expected
    println(num1) 
    
    //multiplication and division by same factor, hence num1 should ideally remain unchanged
    num1 = num1 * factor / factor 
    
    //prints 249.99999999999997, but I was expecting 250.0
    println(num1)
 
}

Why am I losing on precision?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
iCantC
  • 2,852
  • 1
  • 19
  • 34
  • whenever you want to get the precise value of decimal values like in case when you are dealing with monetary numbers, then use BigDecimal not float, not double – Youssef Idraiss Dec 24 '21 at 06:35
  • I thought compiler optimisation phase would have detected that, `num1` was successively multiplied and divided by the same number and the entire operation was completely useless. – iCantC Dec 24 '21 at 06:49
  • Just for the lolz: [Never trust floating point arithmetics (`ideone.com`)](https://ideone.com/sJkE7q). – Turing85 Dec 24 '21 at 06:50

0 Answers0