java 2 decimal places code example
Example 1: decimal up to 6 places in java
double num = 1.34567;
System.out.format("%.4f", num);
Example 2: java double 2 decimal
String result = String.format("%.2f", value);
Example 3: specify decimal places java
double test = 12.15;
DecimalFormat df = new DecimalFormat("#.0");
System.out.println(df.format(test)); // Console: 12.2
//
// . - indicates where to put the decimal seperator
// 0 - prints a digit if provided, 0 otherwise
Example 4: how to set 2 decimal places in java
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));
Example 5: how to limit double decimal places java
package com.mkyong;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalExample {
private static DecimalFormat df2 = new DecimalFormat("#.##");
public static void main(String[] args) {
double input = 3.14159265359;
System.out.println("double : " + input);
System.out.println("double : " + df2.format(input)); //3.14
// DecimalFormat, default is RoundingMode.HALF_EVEN
df2.setRoundingMode(RoundingMode.DOWN);
System.out.println("\ndouble : " + df2.format(input)); //3.14
df2.setRoundingMode(RoundingMode.UP);
System.out.println("double : " + df2.format(input)); //3.15
}
}
Copy
Example 6: 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