How to convert String to Long in Kotlin?

前端 未结 11 1208
旧时难觅i
旧时难觅i 2021-01-31 13:00

So, due to lack of methods like Long.valueOf(String s) I am stuck.

How to convert String to Long in Kotlin?

11条回答
  •  天命终不由人
    2021-01-31 13:37

    1. string.toLong()

    Parses the string as a [Long] number and returns the result.

    @throws NumberFormatException if the string is not a valid representation of a number.

    2. string.toLongOrNull()

    Parses the string as a [Long] number and returns the result or null if the string is not a valid representation of a number.

    3. str.toLong(10)

    Parses the string as a [Long] number and returns the result.

    @throws NumberFormatException if the string is not a valid representation of a number.

    @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.

    public inline fun String.toLong(radix: Int): Long = java.lang.Long.parseLong(this, checkRadix(radix))
    

    4. string.toLongOrNull(10)

    Parses the string as a [Long] number and returns the result or null if the string is not a valid representation of a number.

    @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.

    public fun String.toLongOrNull(radix: Int): Long? {...}
    

    5. java.lang.Long.valueOf(string)

    public static Long valueOf(String s) throws NumberFormatException
    

提交回复
热议问题