0
0
KotlinHow-ToBeginner · 2 min read

Kotlin How to Convert String to Double with Examples

In Kotlin, you can convert a string to a double using the toDouble() function like this: val number = "3.14".toDouble().
📋

Examples

Input"3.14"
Output3.14
Input"0.0"
Output0.0
Input"-123.456"
Output-123.456
🧠

How to Think About It

To convert a string to a double, think of the string as a number written in text form. You want to change it into a number your program can use for math. Kotlin provides a simple function called toDouble() that reads the string and turns it into a double number.
📐

Algorithm

1
Get the input string that represents a number.
2
Use the <code>toDouble()</code> function on the string to convert it.
3
Store or use the resulting double value.
💻

Code

kotlin
fun main() {
    val str = "3.14"
    val number = str.toDouble()
    println(number)
}
Output
3.14
🔍

Dry Run

Let's trace converting the string "3.14" to a double.

1

Input string

str = "3.14"

2

Convert string to double

number = str.toDouble() -> 3.14

3

Print result

Output: 3.14

StepValue
Input string"3.14"
Converted double3.14
Printed output3.14
💡

Why This Works

Step 1: Using toDouble()

The toDouble() function reads the string and converts it into a double number type.

Step 2: String must be a valid number

The string should represent a valid number format, or else toDouble() will throw an error.

Step 3: Result is a Double type

After conversion, you get a value of type Double that you can use in calculations.

🔄

Alternative Approaches

toDoubleOrNull()
kotlin
fun main() {
    val str = "abc"
    val number = str.toDoubleOrNull()
    println(number)
}
This method returns null instead of throwing an error if the string is not a valid number.
Using java.lang.Double.parseDouble()
kotlin
fun main() {
    val str = "3.14"
    val number = java.lang.Double.parseDouble(str)
    println(number)
}
This uses Java's parsing method but behaves similarly to <code>toDouble()</code>.

Complexity: O(n) time, O(1) space

Time Complexity

Conversion scans the string once to parse the number, so it takes linear time relative to string length.

Space Complexity

No extra space is needed besides the output double, so space is constant.

Which Approach is Fastest?

toDouble() and java.lang.Double.parseDouble() have similar speed; toDoubleOrNull() adds safety but with minimal overhead.

ApproachTimeSpaceBest For
toDouble()O(n)O(1)Simple, valid numeric strings
toDoubleOrNull()O(n)O(1)Safe conversion with invalid input handling
java.lang.Double.parseDouble()O(n)O(1)Java interoperability or legacy code
💡
Use toDoubleOrNull() to safely convert strings that might not be valid numbers.
⚠️
Trying to convert a non-numeric string with toDouble() causes a crash due to an exception.