DEV Community

loading...

Kotlin Convert String to Long

loizenai
Software Engineer - Founder at https://loizenai.com
・2 min read

https://grokonez.com/kotlin/kotlin-convert-string-long

Kotlin Convert String to Long

In the tutorial, JavaSampleApproach will guide you how to convert Kotlin String to Long.

Related posts:

Working environment:

  • Java 8
  • Kotlin 1.1.61

    I. Kotlin toLong() method

    1 String.toLong(): Long

  • use method signature: public inline fun String.toLong(): Long

package com.javasampleapproach.string2long
fun main(args : Array<String>) {
    // use method:
    // -> public inline fun String.toLong(): Long = java.lang.Long.parseLong(this)
    val number: Long = "123".toLong();
    println(number) // 123
    
    // if the string is not a valid representation of a number
    // -> throw NumberFormatException
    try{
        "12w".toLong();
    }catch(e: NumberFormatException){
        println(e.printStackTrace())
        // -> print on console:
        /*
            java.lang.NumberFormatException: For input string: "12w"
            at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
            at java.lang.Long.parseLong(Long.java:589)
            at java.lang.Long.parseLong(Long.java:631)
            at com.javasampleapproach.string2long.ConvertString2LongKt.main(ConvertString2Long.kt:12)
        */
    }
}
  • Strig.toLong() will throw a NumberFormatException if the string is not a valid representation of a number.
  • String.toLong() just uses Integer.parseLong of Java for converting -> detail: public inline fun String.toLong(): Long = java.lang.Long.parseLong(this)

2 String.toLong(radix: Int): Long

If we want to work with radix, we can use another method signature toLong(radix: Int)
-> detail: public inline fun String.toLong(radix: Int): Long = java.lang.Long.parseLong(this, checkRadix(radix))

More at:

https://grokonez.com/kotlin/kotlin-convert-string-long

Kotlin Convert String to Long

Discussion (0)