第一种方式:
// 对结果进行四舍五入并保留三位小数
double roundedQuotient = (int)((quotient+0.0005) * 1000.0) / 1000.0;
第二种方式:
// 对结果进行四舍五入并保留三位小数
double roundedQuotient = Math.round(quotient * 1000.0) / 1000.0;
完整代码:
package com.qf.demo0720pratique;
/*
16.求两个数之商,要求对结果小数点后四舍五入保留三位小数。
*/
public class Demo16 {
public static void main(String[] args) {
double a = 10.0; // 被除数
double b = 3.0; // 除数
double quotient = a / b; // 计算商
// 对结果进行四舍五入并保留三位小数
double roundedQuotient = (int)((quotient+0.0005) * 1000.0) / 1000.0;
// 对结果进行四舍五入并保留三位小数
//double roundedQuotient = Math.round(quotient * 1000.0) / 1000.0;
System.out.println("商:" + roundedQuotient);
}
}