Convert an integer to a string in Kotlin
This article explores different ways to convert an integer to a string in Kotlin. If the integer is negative, the sign should be preserved.
1. Using toString() function
The recommended solution is to use the toString() function that returns the string representation of the specified argument.
|
1 2 3 4 5 6 |
fun main() { val n = Int.MAX_VALUE val s = n.toString() println(s) } |
2. Using String.format() function
Alternatively, you can use the String.format() function, which returns a formatted string by substituting the specified arguments.
|
1 2 3 4 5 6 |
fun main() { val n = Int.MAX_VALUE val s = String.format("%d", n) println(s) } |
3. Using StringBuilder.append() function
Another plausible way to convert an integer to a string is using the append() function of the StringBuilder class, which is overloaded to accept data of any type.
|
1 2 3 4 5 6 |
fun main() { val n = Int.MAX_VALUE val s = StringBuilder().append(n).toString() println(s) } |
4. Using DecimalFormat.format() function
DecimalFormat class provides a variety of features to parse and format numbers. We can use it to format an integer to produce a string, as shown below:
|
1 2 3 4 5 6 |
fun main() { val n = Int.MAX_VALUE val s = java.text.DecimalFormat().format(n) println(s) // prints 2,147,483,647 } |
5. Using Plus Operator
Finally, you can concatenate the given integer with an empty string using the + operator or the plus() function to produce the string representation of the integer.
|
1 2 3 4 5 6 |
fun main() { val n = Int.MAX_VALUE val s = "" + n println(s) } |
That’s all about converting an integer to a string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)