The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

Converting Numbers to Strings

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;
String s1 = "" + i; //Concatenate "i" with an empty string;
                    //conversion is handled for you.
String s2 = String.valueOf(i);  //The valueOf class method.
String s3 = Integer.toString(i); //The toString class method.
The ToStringDemo (in a .java source file) 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(s.substring(0, dot).length()
                           + " digits before decimal point.");
        System.out.println(s.substring(dot+1).length()
                           + " digits after decimal point.");
    }
}
The output of this program is:
3 digits before decimal point.
2 digits after decimal point.
The toString method called by this program is the class method. Each of the number classes has an instance method called toString, which you call on an instance of that type.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.