Java保留小数点后2位
时间: 2023-05-29 22:05:04 浏览: 82
在Java中保留小数点后2位有几种方法:
1. 使用DecimalFormat类
DecimalFormat类可以将数字格式化为指定格式的字符串,例如保留小数点后2位可以使用“0.00”作为格式化字符串。
示例代码:
```java
double num = 3.1415926;
DecimalFormat df = new DecimalFormat("0.00");
String result = df.format(num);
System.out.println(result); // 输出3.14
```
2. 使用String.format()方法
String类的format()方法可以将字符串格式化为指定格式的字符串,其中“%.2f”表示保留小数点后2位。
示例代码:
```java
double num = 3.1415926;
String result = String.format("%.2f", num);
System.out.println(result); // 输出3.14
```
3. 使用Math.round()方法
Math.round()方法可以将小数点后第3位四舍五入,然后再除以100得到保留小数点后2位的结果。
示例代码:
```java
double num = 3.1415926;
double result = Math.round(num * 100) / 100.0;
System.out.println(result); // 输出3.14
```
相关问题
java保留小数点后两位
有多种方法可以在Java中保留小数点后两位,以下是其中几种:
1. 使用DecimalFormat类
```java
double num = 3.1415926;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(num));
```
输出结果为:3.14
2. 使用String.format方法
```java
double num = 3.1415926;
String result = String.format("%.2f", num);
System.out.println(result);
```
输出结果为:3.14
3. 使用Math.round方法
```java
double num = 3.1415926;
double result = Math.round(num * 100.0) / 100.0;
System.out.println(result);
```
输出结果为:3.14
Java如何保留小数点后两位
在Java中,有几种方法可以实现保留小数点后两位的效果。其中一种方法是使用BigDecimal类和setScale()方法。例如,以下是一个使用BigDecimal和setScale()方法来保留两位小数的示例:
public static String format1(double value) {
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(2, RoundingMode.HALF_UP);
return bd.toString();
}
另一种方法是使用DecimalFormat类。以下是一个使用DecimalFormat来保留两位小数的示例:
public static String format2(double value) {
DecimalFormat df = new DecimalFormat("0.00");
df.setRoundingMode(RoundingMode.HALF_UP);
return df.format(value);
}
通过调用format1()或format2()方法,并传入要格式化的数字作为参数,即可获得保留两位小数的结果。希望对你有所帮助! <span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [java、freemarker保留两位小数](https://download.csdn.net/download/weixin_38682161/12784007)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [Java - 保留小数点后两位](https://blog.csdn.net/zouzhigang96/article/details/50467248)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]