English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce tutoriel, nous allons apprendre comment convertir un type de variable double en chaîne de caractères en Java.
class Main { public static void main(String[] args) { //Create a double type variable double num1 = 36.33; double num2 = 99.99; //Convertir double en string //Utiliser valueOf() String str1 = String.valueOf(num1); String str2 = String.valueOf(num2); //Imprimer les variables de chaîne System.out.println(str1); // 36.33 System.out.println(str2); // 99.99 } }
Dans l'exemple précédent, nous avons utilisé la méthode valueOf() de la classe String pour convertir la variable double en chaîne de caractères.
Remarque:C'est la meilleure méthode pour convertir une variable double en chaîne de caractères en Java.
Nous pouvons également utiliser la méthode toString() de la classe Double pour convertir la variable double en chaîne de caractères. Par exemple,
class Main { public static void main(String[] args) { //Create a double type variable double num1 = 4.76; double num2 = 786.56; //Convertir double en string //Utiliser la méthode 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 } }
ici, nous avons utilisé la méthode toString() de la classe Double pour convertir la variable double en chaîne de caractères.
ici, Double est une classe enveloppe de Java. Pour plus d'informations, veuillez visiter Java wrapper classes.
class Main { public static void main(String[] args) { //Create a double type variable double num1 = 347.6D; double num2 = 86.56D; //Convertir double en string // utiliser + symboles String str1 = '' + num1; String str2 = '' + num2; // print string variables System.out.println(str1); // 347.6 System.out.println(str2); // 86.56 } }
Attention à cette ligne,
String str1 = '' + num1;
Here, we use string concatenation operations to convert the double variable to a string. For more information, please visitJava string concatenation.
class Main { public static void main(String[] args) { //Create a double type variable double num = 99.99; //Convert double to string using format() String str = String.format("%f", num); System.out.println(str); // 99.990000 } }
Here, we use the format() method to format the specified double variable into a string. For more information on string formatting, please visitJava String format().