在数字和字符串之间转换

原文: https://docs.oracle.com/javase/tutorial/java/data/converting.html

将字符串转换为数字

通常,程序以字符串对象中的数字数据结束 - 例如,用户输入的值。

包含原始数字类型的Number子类( ByteIntegerDoubleFloatLongShort )各自提供一个名为valueOf的类方法,它将字符串转换为该类型的对象。下面是一个示例, ValueOfDemo ,从命令行获取两个字符串,将它们转换为数字,并对值执行算术运算:

  1. public class ValueOfDemo {
  2. public static void main(String[] args) {
  3. // this program requires two
  4. // arguments on the command line
  5. if (args.length == 2) {
  6. // convert strings to numbers
  7. float a = (Float.valueOf(args[0])).floatValue();
  8. float b = (Float.valueOf(args[1])).floatValue();
  9. // do some arithmetic
  10. System.out.println("a + b = " +
  11. (a + b));
  12. System.out.println("a - b = " +
  13. (a - b));
  14. System.out.println("a * b = " +
  15. (a * b));
  16. System.out.println("a / b = " +
  17. (a / b));
  18. System.out.println("a % b = " +
  19. (a % b));
  20. } else {
  21. System.out.println("This program " +
  22. "requires two command-line arguments.");
  23. }
  24. }
  25. }

当您使用4.587.2作为命令行参数时,以下是程序的输出:

  1. a + b = 91.7
  2. a - b = -82.7
  3. a * b = 392.4
  4. a / b = 0.0516055
  5. a % b = 4.5

Note: Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX() method (for example, parseFloat()) that can be used to convert strings to primitive numbers. Since a primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemo program, we could use:

  1. float a = Float.parseFloat(args[0]);
  2. float b = Float.parseFloat(args[1]);

将数字转换为字符串

有时您需要将数字转换为字符串,因为您需要对其字符串形式的值进行操作。有几种简单的方法可以将数字转换为字符串:

  1. int i;
  2. // Concatenate "i" with an empty string; conversion is handled for you.
  3. String s1 = "" + i;

要么

  1. // The valueOf class method.
  2. String s2 = String.valueOf(i);

每个Number子类都包含一个类方法toString(),它将原始类型转换为字符串。例如:

  1. int i;
  2. double d;
  3. String s3 = Integer.toString(i);
  4. String s4 = Double.toString(d);

ToStringDemo 示例使用toString方法将数字转换为字符串。然后程序使用一些字符串方法来计算小数点前后的位数:

  1. public class ToStringDemo {
  2. public static void main(String[] args) {
  3. double d = 858.48;
  4. String s = Double.toString(d);
  5. int dot = s.indexOf('.');
  6. System.out.println(dot + " digits " +
  7. "before decimal point.");
  8. System.out.println( (s.length() - dot - 1) +
  9. " digits after decimal point.");
  10. }
  11. }

该程序的输出是:

  1. 3 digits before decimal point.
  2. 2 digits after decimal point.