1package com.mkyong;
2
3import java.math.RoundingMode;
4import java.text.DecimalFormat;
5
6public class DecimalExample {
7
8 private static DecimalFormat df2 = new DecimalFormat("#.##");
9
10 public static void main(String[] args) {
11
12 double input = 3.14159265359;
13 System.out.println("double : " + input);
14 System.out.println("double : " + df2.format(input)); //3.14
15
16 // DecimalFormat, default is RoundingMode.HALF_EVEN
17 df2.setRoundingMode(RoundingMode.DOWN);
18 System.out.println("\ndouble : " + df2.format(input)); //3.14
19
20 df2.setRoundingMode(RoundingMode.UP);
21 System.out.println("double : " + df2.format(input)); //3.15
22
23 }
24
25}
26Copy
1double d = 5.921763;
2
3DecimalFormat df = new DecimalFormat("#.00");
4String string = df.format(d);
5
6// string = "5.92"
1double input = 3.14159265359;
2System.out.format("double : %.2f", input); // 3.14
3System.out.println("double : " + String.format("%.2f", input)); // 3.14