- 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 - toIntOrNull() Function
The Kotlin string toIntOrNull() function is used to convert or parse the string as an Int 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 toIntOrNull() function −
fun String.toIntOrNull(): Int? fun String.toIntOrNull(radix: Int): Int?
Parameters
This function accepts a radix parameter, which represents the base of the number system to use to parse the string.
Return value
This function returns an Int if the string is a valid representation of the number. Otherwise; null.
Example 1: Convert a string into Int
Following is the basic example of converting a string to an int using the toIntOrNull() function −
fun main() {
val number_str = "102510"
val int_num = number_str.toIntOrNull()
println(int_num)
}
Output
Following is the output −
102510
Example 2: Convert Binary String into Decimal
In this example, we use the toIntOrNull() function with a radix parameter to convert a binary string to a decimal integer −
fun main() {
val binaryString = "1101"
// Binary to Decimal
val binaryNumber = binaryString.toIntOrNull(2)
println("decimal number:" + binaryNumber)
}
Output
Following is the output −
decimal number:13
Example 3: Convert HexaDecimal String into Decimal
In this example, we use the toIntOrNull() function with a radix parameter to convert a hexadecimal string to a decimal integer −
fun main() {
val hexString = "1A3F"
// convert hexadecimal to decimal
val hexNumber = hexString.toIntOrNull(16)
println("Decimal Number: " + hexNumber)
}
Output
Following is the output −
Decimal Number: 6719