Kotlin parse double from string
10,002
Solution 1
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()
Solution 2
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")
}
Related videos on Youtube
Author by
daliaessam
Updated on June 04, 2022Comments
-
daliaessam almost 2 years
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.
-
dbl almost 5 yearsPlease consider how would this implementation fail if the string is one of
"9999 min"
,"area 51"
,"3 boys"
,"test 123 test"
-
daliaessam almost 5 yearsthis needs to update to match Doubles not Int only.