Sling Academy
Home/Kotlin/Converting Strings to Numbers in Kotlin

Converting Strings to Numbers in Kotlin

Last updated: November 29, 2024

Understanding String to Number Conversion in Kotlin

Converting strings to numbers is a common task in programming. Kotlin, being a modern language, offers a variety of methods to convert strings into numeric types. In this article, we'll explore different ways you can achieve this conversion in Kotlin.

Using toInt() and toDouble()

Kotlin provides toInt() and toDouble() functions to convert strings to integer and double values respectively. These functions will throw a NumberFormatException if the string format is not valid for a number.


fun main() {
    val number: String = "123"
    val integer = number.toInt() // Converts to Int
    println("Integer value: ", integer)

    val decimal: String = "123.45"
    val double = decimal.toDouble() // Converts to Double
    println("Double value: ", double)
}

Safe Conversion with toIntOrNull() and toDoubleOrNull()

If you prefer to handle the conversion more safely without risking exceptions, use the toIntOrNull() and toDoubleOrNull() functions. These functions return null if the string cannot be parsed, which you can handle using Kotlin's null safety features.


fun main() {
    val number: String = "123a"
    val integer = number.toIntOrNull() // Returns null
    if (integer != null) {
        println("Converted Integer: ", integer)
    } else {
        println("Conversion failed for integer")
    }

    val decimal: String = "123.45a"
    val double = decimal.toDoubleOrNull() // Returns null
    if (double != null) {
        println("Converted Double: ", double)
    } else {
        println("Conversion failed for double")
    }
}

Dealing with Locale-Specific Formats

Kotlin also allows you to use NumberFormat for parsing numbers in a locale-specific format. This can be particularly useful for applications that must handle numeric formats specific to different geographical locations.


import java.text.NumberFormat
import java.util.Locale

fun main() {
    val germanNotCompliant = "1.234,56"
    val germanLocale = Locale.GERMANY

    val formatter = NumberFormat.getNumberInstance(germanLocale)
    val number = formatter.parse(germanNotCompliant)?.toDouble()
    println("German format parsed number: ", number)
}

Error Handling

When performing conversions, it's crucial to handle errors or unexpected inputs. Utilize Kotlin’s try-catch block to handle any NumberFormatException that may occur with the direct conversion functions like toInt() or toDouble().


fun main() {
    try {
        val invalidNumber = "abc"
        val number = invalidNumber.toInt()
        println("This line will not be executed")
    } catch (e: NumberFormatException) {
        println("Caught NumberFormatException: ", e.message)
    }
}

Conclusion

In Kotlin, converting strings to numbers can be achieved through multiple ways with built-in safety features. Although functions like toInt and toDouble directly perform conversions, it’s often practical to use safer alternatives like toIntOrNull or toDoubleOrNull to avoid exceptions. Additionally, for locale-specific needs, the use of NumberFormat ensures broader applicability in real-world applications.

Next Article: Advanced String Manipulation Techniques in Kotlin

Previous Article: Converting Numbers to Strings in Kotlin

Series: Primitive data types in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin