Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
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:Theint 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.ToStringDemo
example uses thetoString
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:The output of this program is: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."); } }The3 digits before decimal point. 2 digits after decimal point.toString
method called by this program is the class method. Each of the number classes has an instance method calledtoString
, which you call on an instance of that type.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.