
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
Kotlin String - toDoubleOrNull() Function
The Kotlin string toDoubleOrNull() function is used to convert or parse the string as a double (a floating-point number) and returns the result. If the string is not converted or not a valid representation of a number then it will return null.
Syntax
Following is the syntax of the Kotlin string toDoubleOrNull() function −
fun String.toDoubleOrNull(): Int?
Parameters
This function does not accepts any parameters.
Return value
This function returns a double value if the string a valid floating-point number. Otherwise; null.
Example 1: Convert a Number String into Double
Following is the basic example of converting a number string to a double value using the toDoubleOrNull() function −
fun main() { val number_str = "102510" val int_num = number_str.toDoubleOrNull() println("Double Value: " + int_num) }
Output
Following is the output −
Double Value: 102510.0
Example 2: If a String is not a Valid Number String
Let's see another example of the toDoubleOrNull() function. If the string is not a valid number it will return null −
fun main() { val String = "1234abc" // conver string to Double val Number = String.toDoubleOrNull() println("Double Value:" + Number) }
Output
Following is the output −
Double Value:null
Example 3: Use Conditional Statement
In this example, we use the toDoubleOrNull() function and handling nullable result using the if-else statement −
fun main() { val input = "456.78" // convert to double val result = input.toDoubleOrNull() if (result != null) { println("Converted to double: $result") } else { println("Invalid number!") } }
Output
Following is the output −
Converted to double: 456.78