java 小除以大保留小数
时间: 2023-11-18 20:06:25 浏览: 43
你可以使用Java中的`DecimalFormat`类来保留小数,实现小除以大保留小数的功能。以下是示例代码:
```java
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
int small = 3;
int big = 5;
double result = (double) small / big;
DecimalFormat df = new DecimalFormat("#.00"); // 保留两位小数
String formattedResult = df.format(result);
System.out.println(formattedResult); // 输出结果为0.60
}
}
```
在此示例中,我们将一个整数`small`除以另一个整数`big`,得到一个小数`result`。然后,我们使用`DecimalFormat`类将小数格式化为包含两位小数的字符串`formattedResult`。最后,我们将格式化后的结果输出到控制台。
需要注意的是,在进行小除以大的计算时,需要将其中一个整数强制转换为`double`类型,以便得到正确的小数结果。
相关问题
java doule类型除以10000保留2位小数
你可以使用Java的DecimalFormat类来将double类型的数值保留两位小数。下面是一个示例代码:
```java
double num = 123456.789;
double result = num / 10000;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(result));
```
输出结果为:12.35
java math.round保留小数
在Java中,有几种方法可以用于保留小数点后两位。其中一种常用的方法是使用Math.round函数。通过将要保留小数位数的数值乘以100,然后使用Math.round函数进行四舍五入,再将结果除以100,即可得到保留两位小数的数值。
具体代码如下:
```
double num = Math.round(5.2544555 * 100) * 0.01;
System.out.println(num);
```
这段代码会将5.2544555保留两位小数后输出为5.25。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [java 常用四舍五入保留小数点后两位方法](https://blog.csdn.net/qq_38463737/article/details/121294156)[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_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [[Java]保留数值后2位的几种方法](https://blog.csdn.net/u010188178/article/details/98091515)[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_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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://csdnimg.cn/download_wenku/file_type_ask_c1.png)