Java中数据格式化类DecimalFormat中八种舍入模式(Rounding Mode)
DecimalFormat用法:
double value = 11110.82;
//舍入模式
RoundingMode roundingMode = RoundingMode.HALF_UP;
DecimalFormat df = new DecimalFormat("###,###.0");
df.setRoundingMode(roundingMode);
String result = df.format(value);
System.out.println(result);
RoundingMode共有八种,分别如下:
1. UP与DOWN的区别
RoundingMode.UP: 向远离零点方向舍入
RoundingMode.DOWN: 向零点方向舍入(截断数字)
假设保留整数,例子如下:
UP | DOWN | |
---|---|---|
-1.5 | -2 | -1 |
-0.3 | -1 | 0 |
0 | 0 | 0 |
0.3 | 1 | 0 |
1.5 | 2 | 1 |
2. CEILING和FLOOR的区别
RoundingMode.CEILING: 向正无穷方法舍入
RoundingMode.FLOOR: 向负无穷方向舍入
假设保留整数,例子如下:
CEILING | FLOOR | |
---|---|---|
-1.5 | -1 | -2 |
-0.3 | 0 | -1 |
0 | 0 | 0 |
0.3 | 1 | 0 |
1.5 | 2 | 1 |
3. HALF_UP、HALF_DOWN和HALF_EVEN区别
假设要处理的那一位数字为n,
如果n大于5,则和RoundingMode.UP舍入方式一致,向远离零点方向舍入
如果n小于5, 则和RoundingMode.DOWN舍入方式一致,向零点方向舍入。
如果n等于5,
RoundingMode.HALF_UP: 向远离零点方向舍入;(通常意义上的四舍五入)
RoundingMode.HALF_DOWN: 向零点方向舍入;
RoundingMode.HALF_EVEN: 取最近两个数中的偶数;
假设保留整数,例子如下:
HALF_UP | HALF_DOWN | HALF_EVEN | |
---|---|---|---|
-1.6 | -2 | -2 | -2 |
-1.5 | -2 | -1 | -2 |
-0.5 | -1 | 0 | 0 |
-0.3 | 0 | 0 | 0 |
0.3 | 0 | 0 | 0 |
0.5 | 1 | 0 | 0 |
1.5 | 2 | 1 | 2 |
1.6 | 2 | 2 | 2 |
附测试代码:
public class Test {
public static void main(String[] args) throws Exception {
RoundingMode[] modes = {RoundingMode.HALF_UP, RoundingMode.HALF_DOWN, RoundingMode.HALF_EVEN};
double[] values = {-1.6, -1.5, -0.5, -0.3, 0.3, 0.5, 1.5, 1.6};
test(values, modes);
}
private static void test(double[] values, RoundingMode[] modes) {
for (double value : values) {
System.out.println();
for (RoundingMode mode : modes) {
System.out.print(fix(value, mode) + " ");
}
}
}
private static String fix(double value, RoundingMode mode) {
DecimalFormat df = new DecimalFormat("###,###");
df.setRoundingMode(mode);
return df.format(value);
}
}
4. UNNECESSARY作用
RoundingMode.UNNECESSARY: 只有当要处理的那一位数字为零时不抛出异常,并进行处理, 其他情况都会抛出异常。
假设保留整数,例子如下:
UNNECESSARY | |
---|---|
-1.2 | throw ArithmeticException |
-1.0 | -1 |
0 | 0 |
1.0 | 1 |
1.2 | throw ArithmeticException |
测试代码如下:
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class Test {
public static void main(String[] args) throws Exception {
RoundingMode[] modes = {RoundingMode.HALF_UP, RoundingMode.HALF_DOWN, RoundingMode.HALF_EVEN};
double[] values = {-1.6, -1.5, -0.5, -0.3, 0.3, 0.5, 1.5, 1.6};
test(values, modes);
}
private static void test(double[] values, RoundingMode[] modes) {
for (double value : values) {
System.out.println();
for (RoundingMode mode : modes) {
System.out.print(fix(value, mode) + " ");
}
}
}
private static String fix(double value, RoundingMode mode) {
DecimalFormat df = new DecimalFormat("###,###");
df.setRoundingMode(mode);
return df.format(value);
}
}