Java保留三位小数四舍五入使用round()
时间: 2024-10-05 09:04:25 浏览: 84
在Java中,如果你想对一个double类型的数值进行保留三位小数并四舍五入,你可以使用`Math.round()`函数配合`java.text.DecimalFormat`来进行操作。首先,你需要将double转换为BigDecimal,这是因为`round()`方法在处理浮点数时可能会有精度问题,而BigDecimal则能精确地进行计算。
以下是一个示例:
```java
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
double number = 3.141592653589793238;
BigDecimal bd = new BigDecimal(number);
bd = bd.setScale(3, RoundingMode.HALF_UP); // 四舍五入到第三位小数
int roundedInt = bd.intValueExact(); // 转换为int并保持原有精度
DecimalFormat df = new DecimalFormat("#.000");
String formattedNumber = df.format(roundedInt);
System.out.println("Rounded number: " + formattedNumber);
}
}
```
在这个例子中,`setScale(int scale, RoundingMode roundingMode)`方法设置了精度为3,并使用`HALF_UP`模式进行四舍五入。`intValueExact()`用于从BigDecimal转换回整数,以保留原始的精度。
阅读全文
相关推荐


















