java除法保留1位小数
时间: 2023-12-10 14:25:29 浏览: 30
要在Java中进行除法并保留一位小数,可以使用以下代码:
```java
public static String division(int a ,int b){
String result = "";
float num =(float)a/b;
DecimalFormat df = new DecimalFormat("0.0");
result = df.format(num);
return result;
}
```
这段代码中,我们使用了`DecimalFormat`类来格式化除法结果。通过传入格式化模式`"0.0"`,我们告诉它保留一位小数。然后,我们将除法结果格式化为字符串并返回。
你也可以使用其他方法来实现相同的效果。例如,使用`NumberFormat`类来设置精确到小数点后一位,如下所示:
```java
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMaximumFractionDigits(1);
float result = (float) a / b;
String formattedResult = numberFormat.format(result);
```
这段代码中,我们首先创建了一个`NumberFormat`对象,并使用`setMaximumFractionDigits(1)`方法设置精确到小数点后一位。然后,我们进行除法运算并将结果格式化为字符串。
无论你选择使用`DecimalFormat`还是`NumberFormat`,都可以达到保留一位小数的效果。
代码来源: https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java
代码来源: https://www.cnblogs.com/happyday56/p/11224256.html
参考资料: https://www.cnblogs.com/dtwangsheng/p/10151866.html