Convert between numbers and strings
Convert string to number
Typically, a program ends with numeric data in a string object - for example, a value entered by a user.
Packaging original number type( Byte,Integer,Double,Float,Long and Short )Each of the Number subclasses of provides a class method called valueOf that converts a string to an object of that type. Here is an example ValueOfDemo , which takes two strings from the command line, converts them to numbers, and performs arithmetic on the values:
public class ValueOfDemo { public static void main(String[] args) { // this program requires two // arguments on the command line if (args.length == 2) { // convert strings to numbers float a = (Float.valueOf(args[0])).floatValue(); float b = (Float.valueOf(args[1])).floatValue(); // do some arithmetic System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); } else { System.out.println("This program " + "requires two command-line arguments."); } } }
The following is the output of the program when using 4.5 and 87.2 as command line parameters:
a + b = 91.7 a - b = -82.7 a * b = 392.4 a / b = 0.0516055 a % b = 4.5
Each Number subclass that wraps the original Number type also provides a parseXXXX() method (for example, parseFloat()), which can be used to convert a string to the original Number. Because the basic type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemo program, we can use:
float a = Float.parseFloat(args[0]); float b = Float.parseFloat(args[1]);
Convert numbers to strings
Sometimes you need to convert a number to a string, because you need to operate on the value in the form of a string. There are several simple 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 Number subclass contains a class method toString(), which converts its basic type to a string, for example:
int i; double d; String s3 = Integer.toString(i); String s4 = Double.toString(d);
ToStringDemo The example uses the toString method to convert a number to a string, and then the program uses some string methods to calculate 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.