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 roundOff = Math.round(a * 100.0) / 100.0;
2// Or
3double roundOff = (double) Math.round(a * 100) / 100;
4// both have the same output.
1class round{
2 public static void main(String args[]){
3
4 double a = 123.13698;
5 double roundOff = Math.round(a*100)/100;
6
7 System.out.println(roundOff);
8}
9}
10
1import java.math.RoundingMode;
2import java.text.DecimalFormat;
3
4public class DecimalExample {
5 private static DecimalFormat df = new DecimalFormat("0.00");
6 public static void main(String[] args) {
7 double input = 1205.6358;
8
9 System.out.println("salary : " + input);
10
11 // DecimalFormat, default is RoundingMode.HALF_EVEN
12 System.out.println("salary : " + df.format(input)); //1205.64
13
14 df.setRoundingMode(RoundingMode.DOWN);
15 System.out.println("salary : " + df.format(input)); //1205.63
16
17 df.setRoundingMode(RoundingMode.UP);
18 System.out.println("salary : " + df.format(input)); //1205.64
19 }
20}