daliaessam
daliaessam

Reputation: 1666

Kotlin parse double from string

In Kotlin how to parse a double or float number from string like this:

var st: String? = "90 min"

tried to use toDoubleOrNull but always returns 0 or null.

Upvotes: 3

Views: 15577

Answers (4)

guipivoto
guipivoto

Reputation: 18677

You can try (assuming you have only one sequence of numbers in your string).

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")
}

Upvotes: 1

forpas
forpas

Reputation: 164099

If you are certain that the number is always at the start, then use split() with space as delimiter and from the returned list take the 1st item and parse it to Double:

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

If there is a case of spaces at the start or in between, use this:

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

And another way with substringBefore():

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

Or if there is only 1 integer number in the string, remove every non numeric char with replace():

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

Upvotes: 2

Sachin Soma
Sachin Soma

Reputation: 3802

This should work...

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

Upvotes: 0

Piero
Piero

Reputation: 57

It depends on what you need. If you just have to get 90 and the string is formatted always in the same way you can just

var string = "90 min"
var floatFromString = string.substring(0,2).toFloat()

but it's better to learn how to use LocalDate and DateTimeFormatter

Upvotes: -2

Related Questions