How to extract a float from a string in Kotlin

1 Answer

0 votes
fun main() {
    val text = "The price is 148.95 dollars"
    val floatRegex = Regex("[-+]?\\d*\\.\\d+|\\d+")

    val matchResult = floatRegex.find(text)

    if (matchResult != null) {
        val number = matchResult.value.toDouble()
        println("Extracted float: %.2f".format(number))
    } else {
        println("No float found.")
    }
}


 
  
/*
run:
 
Extracted float: 148.95

*/

 



answered Jul 29, 2025 by avibootz
...