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

JavaServer Side Programming

This method accepts a format String and arguments (varargs) and returns a String object of the given variable(s) in the specified format.

You can format a double value into a String using the format() method. To it pass “%f” as the format string (along with the required double value).

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();
      String result = String.format("%f", d);
      System.out.println("The result is: "+result);
   }
}

Output

Enter a double value:
2548.2325
The result is: 2548.2325

Example

Live Demo

public class Sample{
   public static void main(String args[]){
      double val = 22588.336;
      String str = String.format("%f", val);
      System.out.println(str);
   }
}

Output

22588.336000

raja
Published on 08-Feb-2021 11:29:41
Advertisements