有时您需要将数字转换为字符串,因为您需要对其字符串形式的值进行操作。有几种简单的方法可以将数字转换为字符串:
int i; // Concatenate "i" with an empty string; conversion is handled for you. String s1 = "" + i;
或者
// The valueOf class method. String s2 = String.valueOf(i);
每个Number子类都包含一个类方法 ,toString()它将其原始类型转换为字符串。例如:
int i; double d; String s3 = Integer.toString(i); String s4 = Double.toString(d);
该ToStringDemo示例使用该toString()方法将数字转换为字符串。然后程序使用一些字符串方法来计算小数点前后的位数:
public class ToStringDemo { public static void main(String[] args) { double d = 858.48; String s = Double.toString(d); int dot = s.indexOf('.'); System.out.println(dot + " digits " + "before decimal point."); System.out.println( (s.length() - dot - 1) + " digits after decimal point."); } }
这个程序的输出是:
3 digits before decimal point. 2 digits after decimal point.