Java - Convert integer to string [duplicate]

2019-01-01 10:08发布

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".

7条回答
初与友歌
2楼-- · 2019-01-01 10:26

This will do. Pretty trustworthy. : )

    ""+number;

Just to clarify, this works and acceptable to use unless you are looking for micro optimization.

查看更多
人间绝色
3楼-- · 2019-01-01 10:32

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();
查看更多
裙下三千臣
4楼-- · 2019-01-01 10:33

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();
查看更多
倾城一夜雪
5楼-- · 2019-01-01 10:36

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();
}
查看更多
爱死公子算了
6楼-- · 2019-01-01 10:37

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.

查看更多
琉璃瓶的回忆
7楼-- · 2019-01-01 10:42

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)
查看更多
登录 后发表回答