java中对double小数四舍五入保留两位小数
时间: 2025-01-19 08:13:24 浏览: 55
在Java中,你可以使用`java.text.DecimalFormat`或者`Math`类配合`BigDecimal`来进行小数的四舍五入并保留两位。以下是两种方法:
1. 使用`DecimalFormat`:
```java
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
double number = 3.14159;
DecimalFormat df = new DecimalFormat("#.00");
String roundedNumber = df.format(number);
System.out.println(roundedNumber); // 输出 "3.14"
}
}
```
在这个例子中,`df.format(number)`会将数字格式化为保留两位小数的形式。
2. 使用`Math`和`BigDecimal`:
```java
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
double number = 3.14159;
BigDecimal bd = new BigDecimal(Double.toString(number));
BigDecimal roundedBd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
double roundedNumber = roundedBd.doubleValue();
System.out.println(roundedNumber); // 输出 "3.14"
}
}
```
这里先将double转换成BigDecimal,然后设置精度到两位,并选择四舍五入的方式。
阅读全文
相关推荐


















