Home > OS >  What is the best way in kotlin to convert an Int value to a Double in a certain format
What is the best way in kotlin to convert an Int value to a Double in a certain format

Time:11-18

I have the following numbers: val first: Int = 531241180 val second: Int = 653345

What would be the best way to write a function which could get first and second as input and return the following values:

output of the fist to a Double value 53.1241180

output of the second to a Double value 6.53345

CodePudding user response:

If you are allowed to specify, how many numbers you want to see before dot, you can write something like this, avoiding math operations

fun intToDouble(value: Int, integerPlaces: Int): Double {
    val raw = value.toString()
    val sb = StringBuilder(raw)

    if(integerPlaces < sb.length()) {
        sb.insert(integerPlaces, ".")
    } else {
        return 0.0 // return 0 if operation is illegal
    }
    
    return sb.toString().toDouble()
}
  • Related