Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Kotlin Programming Cookbook

You're reading from   Kotlin Programming Cookbook Explore more than 100 recipes that show how to build robust mobile and web applications with Kotlin, Spring Boot, and Android

Arrow left icon
Product type Paperback
Published in Jan 2018
Publisher
ISBN-13 9781788472142
Length 434 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Aanand Shekhar Roy Aanand Shekhar Roy
Author Profile Icon Aanand Shekhar Roy
Aanand Shekhar Roy
Rashi Karanpuria Rashi Karanpuria
Author Profile Icon Rashi Karanpuria
Rashi Karanpuria
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Installation and Working with Environment 2. Control Flow FREE CHAPTER 3. Classes and Objects 4. Functions 5. Object-Oriented Programming 6. Collections Framework 7. Handling File Operations in Kotlin 8. Anko Commons and Extension Function 9. Anko Layouts 10. Databases and Dependency Injection 11. Networking and Concurrency 12. Lambdas and Delegates 13. Testing 14. Web Services with Kotlin 15. Other Books You May Enjoy

Parsing String to Long, Double, or Int

Kotlin makes it really easy to parse String into other data types, such as Long, Integer, or Double.

In JAVA, Long.parseLong(), or the Long.valueOf() static method is used, which parses the string argument as a signed decimal long and returns a long value, and similarly for other data types such as Int, Double, and Boolean. Let’s see how to achieve it in Kotlin.

Getting ready

You just need a Kotlin editor to write and run your code. We’ll use conversion of Long as an example to discuss parsing with string. Conversion to other data types is quite similar.

How to do it...

To parse the string to a Long data type, we use the .toLong() method with the string. It parses the string as a Long number and returns the result. It throws NumberFormatException if the string is not a valid representation of a number. Later, we will see examples for this.

Converting String to Long

Here's an example that shows parsing of string to Long:

fun main(args: Array<String>) {
val str="123"
print(str.toLong())
}

When you run the preceding code, you will see this output:

123

If you don’t want to deal with the exceptions, you can use .toLongOrNull(). This method parses the string as a Long and returns the result, or null if the string is not a valid representation of a number.

Converting string to Long using string.toLongOrNull()

In this example, we will see how we can parse a string using the .toLongOrNull() method:

fun main(args: Array<String>) {
val str="123.4"
val str2="123"
println(str.toLongOrNull())
println(str2.toLongOrNull())
}

On running the preceding program, the following output is generated:

 null 123

Converting with special radix

All the preceding examples use the base (radix) 10. There are cases when we wish to convert a String to Long but using another base. Both string.toLong() and string.toLongOrNull() can receive a custom radix to be used in the conversion. Let's take a look at its implementation:

  • string.toLong(radix):
    • This 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
  • string.toLongOrNull(radix):
    • This 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

Parsing string to Long with special radix

In the preceding examples, we were parsing strings with radix 10, that is, decimals. By default, the radix is taken as 10, but there are certain situations where we need different radix. For example, in case of parsing a string into a binary or octal number. So now, we will see how to work with radix other than the decimal. Though you can use any valid radix, we will show examples that are most commonly used, such as binary and octal.

  • Binary: Since a binary number is made from 0 and 1, the radix used is 2:
fun main(args: Array<String>) {
val str="11111111"
print(str.toLongOrNull(2)) }

On running the preceding program, the following output is generated:

 255
  • Octal: The octal numeral system, or oct for short, is the base-8 number system and uses the digits 0 to 7. Hence, we will use 8 as a radix:
fun main(args: Array<String>) {
val str="377"
print(str.toLongOrNull(8))
}

On running the preceding program, this output is generated:

 255
  • Decimal: The decimal system has 10 numbers in it (0-9); hence, we will use 10 as radix. Note that radix as 10 is used by default in the methods without the radix arguments (.toLong() , .toLongOrNull()):
fun main(args: Array<String>) {
val str="255"
print(str.toLongOrNull(10))
}

On running the preceding program, the following output is generated:

 255

How it works...

Kotlin uses String’s extension functions such as .toLong() and toLongOrNull() to make things easier. Let’s dive into their implementation.

  • For Long, use this:
public inline fun String.toLong(): Long = java.lang.Long.parseLong(this)

As you can see, internally, it also calls the Long.parseLong(string) Java static method, and it is similar to the other data types.

  • For Short, it's the following:
public inline fun String.toShort(): Short = java.lang.Short.parseShort(this)
  • Use this for Int:
public inline fun String.toInt(): Int = java.lang.Integer.parseInt(this)
  • For parsing with Radix, use the following:
public inline fun String.toLong(radix: Int): Long = java.lang.Long.parseLong(this, checkRadix(radix))

The checkRadix method checks whether the given [radix] is valid radix for string to number and number to string conversion.

There's more...

Let’s quickly see a few other extension functions provided by Kotlin to parse String:

  • toBoolean(): Returns `true` if the content of this string is equal to the word true, ignoring case, and `false` otherwise.
  • toShort(): Parses the string as a [Short] number and returns the result. Also, it throws NumberFormatException if the string is not a valid representation of a number.
  • toShort(radix): Parses the string as a [Short] number and returns the result, throws NumberFormatException if the string is not a valid representation of a number, and throws IllegalArgumentException when [radix] is not a valid radix for the string to number conversion.
  • toInt(): Parses the string as an [Int] number and returns the result and throws NumberFormatException if the string is not a valid representation of a number.
  • toIntOrNull(): Parses the string as an [Int] number and returns the result or `null` if the string is not a valid representation of a number.
  • toIntOrNull(radix): Parses the string as an [Int] number and returns the result or `null` if the string is not a valid representation of a number, or @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
  • toFloat(): Parses the string as a [Float] number and returns the result, and @throws NumberFormatException if the string is not a valid representation of a number.
  • toDouble() : Parses the string as a [Double] number and returns the result, and @throws NumberFormatException if the string is not a valid representation of a number.
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image