1

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.
1

2 Answers 2

2

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?
Sign up to request clarification or add additional context in comments.

3 Comments

I think it is a bug in Kotlin JS API - String.toDouble() must be available for all backends. Fill free to create a report.
@SureshG of course you can use these functions until KT-4497 not fixed, but toInt, toDouble etc are more kotlinish :)
Some possible implementations of toDouble You can find here
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.