Convert Number to String in Java
1. Using Built-in Functions:
- Use the built-in function to convert the number to a string.
public class Main {
public static void main(String[] args)
{
int num = 123;
// Step 1
String str = Integer.toString(num);
System.out.println(str);
}
}
Output
123
2. String Concatenation:
- Check if the number is negative and set a flag.
- Iterate over each digit of the number and convert it to its corresponding character representation.
- Concatenate the characters to form the string.
public class Main {
public static void main(String[] args)
{
int num = 123;
StringBuilder str = new StringBuilder();
boolean isNegative = false;
// Step 1
if (num < 0) {
isNegative = true;
num = -num;
}
// Step 2
while (num > 0) {
str.append((char)('0' + num % 10));
num /= 10;
}
if (isNegative) {
str.append('-');
}
// Step 3
System.out.println(str.reverse().toString());
}
}
Output
123
3. String Formatting:
- Use string formatting functions or methods to convert a number to its string representation.
public class Main {
public static void main(String[] args)
{
int num = 3;
// Step 1
String str = String.format("%d", num);
System.out.println(str);
}
}
Output
3
How to Convert Number to String
Given a numerical value, convert it into a string representation. In this article, we will provide a detailed overview about different ways to convert Number to String in different languages.
Table of Content
- Convert Number to String in C
- Convert Number to String in C++
- Convert Number to String in Java
- Convert Number to String in Python
- Convert Number to String in C#
- Convert Number to String in Javascript