How to convert String to Long in Kotlin?


In this article, we will see how to convert a String to Long in Kotlin using a library function. There are multiple ways to do it. Let's take a couple of examples to demonstrate how it's done.

Example - using toLong()

toLong() is a function that provides the most convenient way to convert a string to a long. In the following example, we will see how we can use toLong() to convert our String.

fun convertToLong(s: String) {

   try {
      val value = s.toLong()
      println("The Long value is: $value")
   }

   catch (ex: NumberFormatException) {
      println("Please enter a number: ")
   }
}
fun main() {
   val str = "1234567890"
   convertToLong(str)
}

Output

Once the above piece of code is executed, it will convert our String "1234567890" to a Long value.

The Long value is: 1234567890

Example - using toLongOrNull()

Like toLong(), we can use another function called toLongOrNull() to convert a String value to Long. In the following example, we will see how to convert a String to Long using toLongOrNull().

fun convertToLong(s: String) {

   try {
      val value = s.toLongOrNull()
      println("The Long value is: $value")
   }
   catch (ex: NumberFormatException) {
      println("Please enter a number: ")
   }
}

fun main() {
   val str = "1234567890"
   convertToLong(str)
}

Output

Once the above piece of code is executed, it will convert our String "1234567890" to a Long value.

The Long value is: 1234567890

Example - java.lang.Long.valueOf()

Kotlin is based on the JVM. Hence, we can use the Java Lang package to convert a String to a Long variable. In the following example, we have used the valueOf() function to convert a String to a Long variable.

fun main() {
   val str = "12345678"
   println("The given string is: " +str)
   val value = java.lang.Long.valueOf(str)
   println("After converting to Long: " +value)
}

Output

One executed, the above piece of code will convert our String "1234567890" to a Long value.

The given string is: 12345678
After converting to Long: 12345678

Updated on: 23-Nov-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements