开发者

Java - Convert integer to string [duplicate]

开发者 https://www.devze.com 2023-02-12 05:10 出处:网络
This question already 开发者_JAVA技巧has answers here: Java int to String - Integer.toString(i) vs new Integer(i).toString()
This question already 开发者_JAVA技巧has answers here: Java int to String - Integer.toString(i) vs new Integer(i).toString() (11 answers) How do I convert from int to String? (20 answers) Closed 8 years ago.

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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消