Given a number:
int number = 1234;
Which would be the "best" way to convert this to a string:
String stringNumber = "1234";
I have tried searching (googling) for an answer but no many seemed "trustworthy".
Given a number:
int number = 1234;
Which would be the "best" way to convert this to a string:
String stringNumber = "1234";
I have tried searching (googling) for an answer but no many seemed "trustworthy".
There are multiple ways:
String.valueOf(number)
(my preference)"" + number
(I don't know how the compiler handles it, perhaps it is as efficient as the above)Integer.toString(number)
Integer class has static method toString() - you can use it:
int i = 1234;
String str = Integer.toString(i);
Returns a String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the toString(int, int) method.
Always use either String.valueOf(number)
or Integer.toString(number)
.
Using "" + number is an overhead and does the following:
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(number);
return sb.toString();
This will do. Pretty trustworthy. : )
""+number;
Just to clarify, this works and acceptable to use unless you are looking for micro optimization.
The way I know how to convert an integer into a string is by using the following code:
Integer.toString(int);
and
String.valueOf(int);
If you had an integer i, and a string s, then the following would apply:
int i;
String s = Integer.toString(i); or
String s = String.valueOf(i);
If you wanted to convert a string "s" into an integer "i", then the following would work:
i = Integer.valueOf(s).intValue();
This is the method which i used to convert the integer to string.Correct me if i did wrong.
/**
* @param a
* @return
*/
private String convertToString(int a) {
int c;
char m;
StringBuilder ans = new StringBuilder();
// convert the String to int
while (a > 0) {
c = a % 10;
a = a / 10;
m = (char) ('0' + c);
ans.append(m);
}
return ans.reverse().toString();
}
StringBuilder
can just accept the whole integer in one call to append! And it works across all the special cases your code fails for. You can replace this entire thing with StringBuilder sb = new StringBuilder(); sb.append(intValue); return sb.toString();