Home > Net >  How do you change a double, float and int to a double to be able to add different data types?
How do you change a double, float and int to a double to be able to add different data types?

Time:03-12

fun main() {
    var t=sumIntegers(arrayOf("you",6.7,8.70F,9)
    println(t)
    }
    fun sumIntegers(medly:Array<Any>):Double{
    var sum=0.0
    medly.forEach{p->
    if (p is Int || p is Doublec||p is Float){
    sum =p.toDouble
       }
     }return sum
}

I have tried toDouble() but it is not working

CodePudding user response:

You can try something like this as well:

fun sumIntegers(medly: Array<Any>): Double{
    return medly.sumOf { if(it is Number) it.toDouble() else 0.0 }
}

CodePudding user response:

val list = arrayOf("you", 6.7, 8.70f, 9)

val result = list
  .filterIsInstance<Number>()
  .sumOf { it.toDouble() }

println(result)
  • Related