//除数
Integer divisor=10;
//被除数
Integer Dividend=3;
double percentage = new BigDecimal(divisor/(double)Dividend).setScale(N,BigDecimal.ROUND_HALF_UP).doubleValue();
例:保留2位小数
public static void main(String[] args) {
int a = 10;
int b = 3;
double result = new BigDecimal(a / (double) b).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(result);
}
结果:
D:\JDK\JDK1.8\jdk1.8.0_231\bin\java.exe ...
3.33
Process finished with exit code 0
BigDecimal.setScale()方法用于格式化小数点,默认用四舍五入方式
格式:setScale(N)表示保留N位小数
例:
setScale(1,BigDecimal.ROUND_DOWN):直接截断,0.21->0.2;0.29->0.2
setScale(1,BigDecimal.ROUND_UP):直接进位,0.21->0.3;0.29->0.3
setScale(1,BigDecimal.ROUND_HALF_UP):四舍五入,0.21->0.2;0.29->0.3
setScaler(1,BigDecimal.ROUND_HALF_DOWN):五舍六入,0.21->0.2;0.25->0.2;0.29->0.3