string format decimal places java code example

Example 1: java string format .2f

String.format("%.2f", 3.45);

Example 2: java string format 2 decimal places

String strDouble = String.format("%.2f", 1.23456);

DecimalFormat df = new DecimalFormat("#.##");
String formatted = df.format(2.456345); 
System.out.println(formatted);

Example 3: java double format

NumberFormat formatter = new DecimalFormat("#0.00");     
System.out.println(formatter.format(4.0));

Example 4: Display double in decimal places java

double input = 3.14159265359;
System.out.format("double : %.2f", input); // 3.14
System.out.println("double : " + String.format("%.2f", input)); // 3.14

Tags:

Java Example