Converting string to double in Kotlin

Feedback


Solution 1:

Assuming the number is consistently located at the beginning, employ

split()

with a space delimiter. Then, retrieve the first item from the resulting list and parse it using

Double

.

val value = st!!.split(" ")[0].toDoubleOrNull()

In case there are any spaces at the beginning or in the middle, utilize this.

val value = st!!.trim().split("\s+".toRegex())[0].toDoubleOrNull() 

Another approach utilizing

substringBefore()

is as follows:

val value = st!!.trim().substringBefore(" ").toDoubleOrNull()

In case the string contains a single integer, eliminate all non-numeric characters using

replace()

.

val value = st!!.replace("\D".toRegex(), "").toDoubleOrNull()


Solution 2:


If your string contains only one sequence of numbers, you may attempt it.

Otherwise, check other answers

val inputString = "123. Test"
val regex = "\d+(\.\d+)?".toRegex()
val match = regex.find(inputString)
if (match != null) {
    println("Result: " + match.value)
} else {
    println("Result: Not found")
}


Solution 3:

This should work…

val pattern = Pattern.compile("\d+") // the regex
val matcher = pattern.matcher("hello123hgj") // your string
val doubles = ArrayList() // results
while (matcher.find())
{ // for each match
  doubles.add(Double.parseDouble(matcher.group())) // convert to double
}

Frequently Asked Questions