'How do you change a double, float and int to a double to be able to add different data types?
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
Solution 1:[1]
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 }
}
Solution 2:[2]
val list = arrayOf("you", 6.7, 8.70f, 9)
val result = list
.filterIsInstance<Number>()
.sumOf { it.toDouble() }
println(result)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arpit Shukla |
| Solution 2 | lukas.j |
