Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin parse double from string

Tags:

android

kotlin

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.

like image 473
daliaessam Avatar asked Feb 20 '26 10:02

daliaessam


1 Answers

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()
like image 178
forpas Avatar answered Feb 21 '26 22:02

forpas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!