Java 数值

取整

1
2
3
4
// 向上取整(天花板)
Math.ceil();
// 向下取整(地板)
Math.floor();

判断两个金额是否相等

注意不能直接使用equal== , 例如: 0.010.010 实际上是一样的

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 比较两个数值是否相等
*/
public static boolean isEqual(Object x, Object y) {
return compareTo(x, y) == 0;
}

/**
* 比较数字大小,x > y返回-1,x = y返回0,x < y返回1
*/
public static int compareTo(Object x, Object y) {
return new BigDecimal(x + "").compareTo(new BigDecimal(y + ""));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
public static void main(String[] args) throws Exception {
BigDecimal a = divide(1, 7, 2, RoundingMode.HALF_EVEN);
BigDecimal b = divide(6, 7, 2, RoundingMode.HALF_EVEN);
System.out.println(a);
System.out.println(b);
System.out.println(CalcUtils.add(a, b));

}

public static BigDecimal divide(Object x, Object y, int bit, RoundingMode mode) {
return new BigDecimal(x + "").divide(new BigDecimal(y + ""), bit, mode);
}
}