English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Básico de Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Tratamento de Exceções Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java程序将双精度(double)类型变量转换为字符串

    Exemplos Java

在本教程中,我们将学习如何在Java中将双精度类型变量转换为字符串。

Exemplo1:Java程序使用valueOf将 double 类型转换为字符串

class Main {
  public static void main(String[] args) {
    //Criação de variável do tipo double
    double num1 = 36.33;
    double num2 = 99.99;
    //将 double 转换为 string
    //使用 valueOf()
    String str1 = String.valueOf(num1);
    String str2 = String.valueOf(num2);
    //打印字符串变量
    System.out.println(str1);    // 36.33
    System.out.println(str2);    // 99.99
  }
}

在上面的示例中,我们使用了String类的valueOf()方法将double变量转换为字符串。

注意:这是Java中将 double 变量转换为字符串的最佳方法。

Exemplo2:Java程序使用toString()将 double 类型转换为字符串

我们还可以使用Double类的toString()方法将double变量转换为字符串。例如,

class Main {
  public static void main(String[] args) {
    //Criação de variável do tipo double
    double num1 = 4.76;
    double num2 = 786.56;
    //将 double 转换为 string
    //使用 toString() 方法
    String str1 = Double.toString(num1);
    String str2 = Double.toString(num2);
    // print string variables
    System.out.println(str1);    // 4.76
    System.out.println(str2);    // 786.56
  }
}

在这里,我们使用了Double类的toString()方法将double变量转换为字符串。

这里,Double是Java的包装类。要了解更多信息,请访问  Classes Wrappers Java

Exemplo3:Java程序使用+运算符将双精度转换为字符串

class Main {
  public static void main(String[] args) {
    //Criação de variável do tipo double
    double num1 = 347.6D;
    double num2 = 86.56D;
    //将 double 转换为 string
    // 使用 + 符号
    String str1 = "" + num1;
    String str2 = "" + num2;
    // print string variables
    System.out.println(str1);    // 347.6
    System.out.println(str2);    // 86.56
  }
}

注意这一行,

String str1 = "" + num1;

Aqui, usamos a operação de concatenação de strings para converter a variável double em uma string. Para mais informações, acesseConexão de Strings Java

Exemplo4:O Java usa format() para converter double em String

class Main {
  public static void main(String[] args) {
    //Criação de variável do tipo double
    double num = 99.99;
    //Conversão de double para string usando format()
    String str = String.format("%f", num);
    System.out.println(str);    // 99.990000
  }
}

Aqui, usamos o método format() para formatar uma variável double em uma string. Para mais informações sobre a formatação de strings, acesseJava String format()

Exemplos Java