1 package com.jdk7.chapter3;
2
3 import java.math.BigDecimal;
4
5 public class Round {
6 //调用java.util.Math进行四舍五入取整
7 public static long getRoundMath(
double dou){
8 return Math.round(dou);
9 }
10
11 //调用java.math.BigDecimal进行不同类别的舍入
12 public static BigDecimal getRoundBigDecimal(
double dou,
int point,
int type){
13 BigDecimal bd =
new BigDecimal(dou);
14 return bd.setScale(point, type);
15 }
16
17 /**
18 * 在BigDecimal类中定义了不同舍入方式的值如下:
19 * public final static int ROUND_UP = 0; //远离0的舍入
20 * public final static int ROUND_DOWN = 1; //接近0的舍入
21 * public final static int ROUND_CEILING = 2; //接近正无穷大的舍入
22 * public final static int ROUND_FLOOR = 3; //接近负无穷大的舍入
23 * public final static int ROUND_HALF_UP = 4; //四舍五入
24 * public final static int ROUND_HALF_DOWN = 5; //向最接近的数字舍入,如果与两个相邻的数字相等,则为ROUND_DOWN模式
25 * public final static int ROUND_HALF_EVEN = 6; //向最接近的数字舍入,如果与两个相邻的数字相等,则向相邻的偶数舍入
26 * public final static int ROUND_UNNECESSARY = 7;
27 *
28 * @param args
29 */
30 public static void main(String[] args) {
31 double dou = 345.987
;
32 System.out.println(getRoundMath(dou));
33 System.out.println(getRoundBigDecimal(dou,0,0
));
34 System.out.println(getRoundBigDecimal(dou,0,1
));
35 System.out.println(getRoundBigDecimal(dou,0,2
));
36 System.out.println(getRoundBigDecimal(dou,0,3
));
37 System.out.println(getRoundBigDecimal(dou,0,4
));
38 System.out.println(getRoundBigDecimal(dou,0,5
));
39 System.out.println(getRoundBigDecimal(dou,0,6
));
40 }
41 }
42
43 执行结果:
44 346
45 346
46 345
47 346
48 345
49 346
50 346
51 346
转载于:https://www.cnblogs.com/celine/p/8299114.html