How to convert String to Long in Kotlin?

前端 未结 11 1011
旧时难觅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条回答
  •  梦毁少年i
    2021-01-31 13:41

    One good old Java possibility what's not mentioned in the answers is java.lang.Long.decode(String).


    Decimal Strings:

    Kotlin's String.toLong() is equivalent to Java's Long.parseLong(String):

    Parses the string argument as a signed decimal long. ... The resulting long value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseLong(java.lang.String, int) method.


    Non-decimal Strings:

    Kotlin's String.toLong(radix: Int) is equivalent to Java's eLong.parseLong(String, int):

    Parses the string argument as a signed long in the radix specified by the second argument. The characters in the string must all be digits of the specified radix ...

    And here comes java.lang.Long.decode(String) into the picture:

    Decodes a String into a Long. Accepts decimal, hexadecimal, and octal numbers given by the following grammar: DecodableString:

    (Sign) DecimalNumeral | (Sign) 0x HexDigits | (Sign) 0X HexDigits | (Sign) # HexDigits | (Sign) 0 OctalDigits

    Sign: - | +

    That means that decode can parse Strings like "0x412", where other methods will result in a NumberFormatException.

    val kotlin_toLong010 = "010".toLong() // 10 as parsed as decimal
    val kotlin_toLong10 = "10".toLong() // 10 as parsed as decimal
    val java_parseLong010 = java.lang.Long.parseLong("010") // 10 as parsed as decimal
    val java_parseLong10 = java.lang.Long.parseLong("10") // 10 as parsed as decimal
    
    val kotlin_toLong010Radix = "010".toLong(8) // 8 as "octal" parsing is forced
    val kotlin_toLong10Radix = "10".toLong(8) // 8 as "octal" parsing is forced
    val java_parseLong010Radix = java.lang.Long.parseLong("010", 8) // 8 as "octal" parsing is forced
    val java_parseLong10Radix = java.lang.Long.parseLong("10", 8) // 8 as "octal" parsing is forced
    
    val java_decode010 = java.lang.Long.decode("010") // 8 as 0 means "octal"
    val java_decode10 = java.lang.Long.decode("10") // 10 as parsed as decimal
    

提交回复
热议问题