How to convert a double value into a Java String using append method?

JavaServer Side ProgrammingProgramming

The append method of the StringBuilder or StringBuffer objects accept a boolean or, char or, char array or, double or, float or, int or, long or, String value as parameter and adds it to the current object.

You can append the required double value to the method and retrieve a String from obtained StringBuffer (or, StringBuilder) objects.

Example

Live Demo

import java.util.Scanner;
public class ConversionOfDouble {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a double value:");
      double d = sc.nextDouble();
      StringBuffer sb = new StringBuffer();
      sb.append(d);
      String result = sb.toString();
      System.out.println("The result is: "+result);
   }
}

Output

Enter a double value:
2548.2325
The result is: 2548.2325

Example

Live Demo

public class Test {
   public static void main(String args[]) {
      double val = 5698.336;
      StringBuffer sb = new StringBuffer();
      sb.append(val);
      String result = sb.toString();
      System.out.println(result);
   }
}

Output

5698.336

raja
Published on 08-Feb-2021 16:00:21
Advertisements