| Developer's Daily | Java Q&A Center |
| main | java | perl | unix | dev directory | web log |
| Question: | How do I convert numeric values to Strings with Java? |
| Answer: |
|
Converting numeric values to Strings with Java has been made pretty easy.
The Let's take a look at a few examples. Assuming that the variable Using
String s = String.valueOf(i);
String s = String.valueOf(f);
String s = String.valueOf(d);
String s = String.valueOf(l);
Using the
String s = new Integer(i).toString();
String s = new Float(f).toString();
String s = new Double(d).toString();
String s = new Long(l).toString();
As an additional example, the simple (some people would call it trivial) Java program shown below demonstrates how this is done in a working Java program:
// Convert.java
// Copyright 1998 DevDaily Interactive, Inc. All Rights Reserved.
class Convert {
public static void main(String[] args) {
int i = 100;
float f = (float) 200.0;
double d = 400.0;
long l = 100000;
String s = new String();
//--------------------------------------------//
// Examples using "valueOf()" method of the //
// String class. //
//--------------------------------------------//
s = String.valueOf(i);
System.out.println ("int i = " + s);
s = String.valueOf(f);
System.out.println ("float f = " + s);
s = String.valueOf(d);
System.out.println ("double d = " + s);
s = String.valueOf(l);
System.out.println ("long l = " + s);
//------------------------------------------------//
// Examples using the "toString()" method of the //
// numeric classes //
//------------------------------------------------//
s = new Integer(i).toString();
System.out.println ("int i = " + s);
s = new Float(f).toString();
System.out.println ("float f = " + s);
s = new Double(d).toString();
System.out.println ("double d = " + s);
s = new Long(l).toString();
System.out.println ("long l = " + s);
}
}
Download the example code If you want to download the
|
Copyright
© 1998-2002 DevDaily Interactive, Inc.
All Rights Reserved.