How to convert String to Long in Kotlin?
Asked Answered
L

12

225

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

How to convert String to Long in Kotlin?

Laureenlaurel answered 22/10, 2013 at 13:36 Comment(0)
L
234

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. string.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
Lisabethlisan answered 23/8, 2017 at 9:0 Comment(0)
B
112

String has a corresponding extension method:

"10".toLong()
Bellows answered 19/11, 2013 at 18:41 Comment(2)
Names have changed in Kotlin, you don't need to worry about where or why, just know in Kotlin that all String have an extension function toLong() as well as toInt() and others. You can use these. Maybe @ilya can update this answer to current Kotlin (remove jet.String reference.)Jews
Just a heads up, if you're iterating a string of digits, they will be chars and [char].toInt() will give you the ascii representation.Newport
R
63

Extension methods are available for Strings to parse them into other primitive types. Examples below:

Runnel answered 13/11, 2015 at 23:41 Comment(1)
str.toLongOrNull() and other similarly named methods are also useful if you can't guarantee that the input will be formatted correctly. With this you can do stuff like str.toLongOrNull()?.let { doSomethingWith(it) } ?: println("Please input a number")Interval
J
11

Note: Answers mentioning jet.String are outdated. Here is current Kotlin (1.0):

Any String in Kotlin already has an extension function you can call toLong(). Nothing special is needed, just use it.

All extension functions for String are documented. You can find others for standard lib in the api reference

Jews answered 22/10, 2013 at 13:36 Comment(0)
L
9

Actually, 90% of the time you also need to check the 'long' is valid, so you need:

"10".toLongOrNull()

There is an 'orNull' equivalent for each 'toLong' of the basic types, and these allow for managing invalid cases with keeping with the Kotlin? idiom.

Lexicography answered 21/5, 2017 at 10:14 Comment(1)
Agreed. Most of the time .toLongOrNull() is what you need.Rissa
L
7

It's interesting. Code like this:

val num = java.lang.Long.valueOf("2");
println(num);
println(num is kotlin.Long);

makes this output:

2
true

I guess, Kotlin makes conversion from java.lang.Long and long primitive to kotlin.Long automatically in this case. So, it's solution, but I would be happy to see tool without java.lang package usage.

Laureenlaurel answered 23/10, 2013 at 8:54 Comment(0)
R
6

In Kotlin, to convert a String to Long (that represents a 64-bit signed integer) is simple.

You can use any of the following examples:

val number1: Long = "789".toLong()
println(number1)                                   // 789

val number2: Long? = "404".toLongOrNull()
println("number = $number2")                       // number = 404

val number3: Long? = "Error404".toLongOrNull()    
println("number = $number3")                       // number = null

val number4: Long? = "111".toLongOrNull(2)         // binary
println("numberWithRadix(2) = $number4")           // numberWithRadix(2) = 7

With toLongOrNull() method, you can use let { } scope function after ?. safe call operator.

Such a logic is good for executing a code block only with non-null values.

fun convertToLong(that: String) {
    that.toLongOrNull()?.let {
        println("Long value is $it")
    }
}
convertToLong("123")                               // Long value is 123
Residentiary answered 12/1, 2019 at 23:18 Comment(0)
B
4

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
Barimah answered 4/1, 2019 at 8:29 Comment(0)
B
1
string.toLong()

where string is your variable.

Bindery answered 19/4, 2018 at 5:52 Comment(0)
C
1

If you don't want to handle NumberFormatException while parsing

 var someLongValue=string.toLongOrNull() ?: 0
Carnivorous answered 16/1, 2019 at 9:25 Comment(0)
E
1

Actually, there are several ways:

Given:

var numberString : String = "numberString" 
// number is the Long value of numberString (if any)
var defaultValue : Long    = defaultValue

Then we have:

+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString is a valid number ?            |  true    | false                 |
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString.toLong()                       |  number  | NumberFormatException |
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString.toLongOrNull()                 |  number  | null                  |
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString.toLongOrNull() ?: defaultValue |  number  | defaultValue          |
+—————————————————————————————————————————————+——————————+———————————————————————+
Eichhorn answered 4/3, 2019 at 10:32 Comment(1)
how can you have defaultValue = Long : defaultValue Where would numberString get used in your example/ I think it ought to be defaultValue = Long : numberString?Cockerel
H
0

Here are several ways to do this:

// Throws exception if number has bad form
val result1 = "5678".toLong()
// Will be null if number has bad form
val result2 = "5678".toLongOrNull()
// Will be the given default if number has bad form
val result3 = "5678"
    .toLongOrNull()
    ?: -1L // The default
// Will be return of the run block if number has bad form
val result4 = "5678"
    .toIntOrNull()
    ?: run {
        // ...
        // return a Long
    }
// Ignores any none-digit character in the string
val result5 = "56abc78"
    .filter { it.isDigit() }
    .joinToString(separator="")
    .toLongOrNull()
Hungry answered 24/9, 2023 at 6:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.