bigDecimal 保留两位小数
时间: 2024-01-12 15:22:35 浏览: 170
以下是使用BigDecimal保留两位小数的示例代码:
```java
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalUtil {
public static String formatDecimal(BigDecimal data) {
if (data == null) {
return "0.00";
}
data = data.setScale(2, RoundingMode.HALF_UP);
return data.stripTrailingZeros().toPlainString();
}
public static void main(String[] args) {
BigDecimal data = new BigDecimal("123.456"); String formattedData = formatDecimal(data);
System.out.println(formattedData); // 输出:123.46
}
}
```
在上述代码中,我们定义了一个`BigDecimalUtil`类,其中包含了一个`formatDecimal`方法,该方法接收一个`BigDecimal`类型的参数,并返回一个保留两位小数的字符串。如果传入的参数为null,则返回"0.00"。在方法内部,我们使用`setScale`方法设置小数位数为2,并使用`RoundingMode.HALF_UP`进行四舍五入。然后,我们使用`stripTrailingZeros`方法去掉小数位无效的0,并使用`toPlainString`方法将结果转换为字符串。
在`main`方法中,我们创建了一个`BigDecimal`对象`data`,并调用`formatDecimal`方法对其进行格式化。最后,我们将格式化后的结果打印出来。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)