Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string:
int i;
// Concatenate "i" with an empty string;
// conversion is handled for you.
String s1 = "" + i;
or
// The valueOf class method.
String s2 = String.valueOf(i);
Each of the
Number
subclasses includes a class method, toString()
, that will convert its primitive type to a string. For example:int i;
double d;
String s3 = Integer.toString(i);
String s4 = Double.toString(d);
The
ToStringDemo
example uses the toString
method to convert a number to a string. The program then uses some string methods to compute the number of digits before and after the decimal point: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.");
}
}
The output of this program is:
3 digits before decimal point.
2 digits after decimal point.