hakim
hakim

Reputation: 3

weird when I pass int parameter I get a different result than when I pass double

fun main() {    
        printFinalTemperature(27.0, "Celsius", "Fahrenheit") { 9/5 * it + 32 }
        printFinalTemperature(350.0, "Kelvin", "Celsius") { it - 273.15 }
        printFinalTemperature(10.0, "Fahrenheit", "Kelvin") { 5.0 / 9.0 * (it - 32) + 273.15 }
}


fun printFinalTemperature(
    initialMeasurement: Double, 
    initialUnit: String, 
    finalUnit: String, 
    conversionFormula: (Double) -> Double
) {
    val finalMeasurement = String.format("%.2f", conversionFormula(initialMeasurement)) // two decimal places
    println("$initialMeasurement degrees $initialUnit is $finalMeasurement degrees $finalUnit.")
}

it give me this result

27.0 degrees Celsius is 59.00 degrees Fahrenheit.

350.0 degrees Kelvin is 76.85 degrees Celsius.

10.0 degrees Fahrenheit is 260.93 degrees Kelvin.`

but when I write 9.0/5.0 rather than 9/5 I get this result

27.0 degrees Celsius is 80.60 degrees Fahrenheit.

350.0 degrees Kelvin is 76.85 degrees Celsius.

10.0 degrees Fahrenheit is 260.93 degrees Kelvin.

why does the result change when I change int to double ? what happened behind the scenes ?

Upvotes: 0

Views: 84

Answers (1)

Benjamin Charais
Benjamin Charais

Reputation: 1368

Decimal division versus Integer division are very likely to have large swings in output values. In the case of your example:

Int division   : 9 / 5 = 1
Double division: 9 / 5 = 1.8

Integers never store any concept of decimals, in Kotlin the design decision was to use Integer based division following the choices of Java. Kotlin Discuss

This specifically works by outright dropping the decimal rather than applying any rounding

Would round up:

Int   : 11 / 4 = 2
Double: 11 / 4 = 2.75

Would round down:

Int   : 9 / 4 = 2
Double: 9 / 4 = 2.25

In general, division with a double will give the correct enough answer (Floating point math does break down in certain circumstances)

Upvotes: 1

Related Questions