Converting Strings to Numbers
Frequently, a program ends up with numeric data in a string object—a value entered by the user, for example.The
Numbersubclasses that wrap primitive numeric types (Byte,Integer,Double,Float,Long, andShort) each provide a class method namedvalueOfthat converts a string to an object of that type. Here is an example,ValueOfDemo, that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values:The following is the output from the program when you use/* * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ 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."); } } }4.5and87.2for the command-line arguments:a + b = 91.7 a - b = -82.7 a * b = 392.4 a / b = 0.0516055 a % b = 4.5
Note: Each of theNumbersubclasses that wrap primitive numeric types also provides aparseXXXX()method (for example,parseFloat()) that can be used to convert strings to primitive numbers. Since a primitive type is returned instead of an object, theparseFloat()method is more direct than thevalueOf()method. For example, in theValueOfDemoprogram, we could use:float a = Float.parseFloat(args[0]); float b = Float.parseFloat(args[1]);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:orint i; String s1 = "" + i; //Concatenate "i" with an empty string; //conversion is handled for you.Each of theString s2 = String.valueOf(i); //The valueOf class method.Numbersubclasses includes a class method,toString(), that will convert its primitive type to a string. For example:Theint i; double d; String s3 = Integer.toString(i); String s4 = Double.toString(d);ToStringDemoexample uses thetoStringmethod 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:/* * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ 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."); } }3 digits before decimal point. 2 digits after decimal point.