Kotlin JS - string to number conversion?

1.9k views Asked by At

How to do String to number conversion in Kotlin JS app. I am Using the following code and having some trouble converting from the HTMLInputElement value to double.

fun c2f(self: Any) {
   console.log("Self object: ${self} ")
   val celsius = document.getElementById("celcius")?.getAttribute("value") as Double
   val fahrenheit = celsius * 1.8 + 32
   console.log("Fahrenheit value: ${fahrenheit} ")
   window.alert("Celcius (${celsius}) -> Fahrenheit (${fahrenheit}) ")
 }
  • Also i am not seeing any toDouble() function on String class as in the case of JVM app.
2

There are 2 answers

3
Suresh On

Answering my own question as this would be helpful for somebody.

You can use the kotlin.js top level parse functions for string <-> Number conversion.

fun parseInt(s: String, radix: Int = 10): Int
fun safeParseInt(s : String) : Int?
fun safeParseDouble(s : String) : Double?
0
tomschrot On

Simply use the String.toXXX() functions, e.g.

val n = "1"
val m = 2 + n.toInt()

val x = "1.1"
val y = 2.0 + x.toFloat()

etc.