java浮点数保留2位小数
时间: 2023-12-10 19:02:26 浏览: 43
在Java中,你可以使用DecimalFormat类来保留浮点数的小数位数。下面是一个示例代码:
```java
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
double number = 123.456789;
DecimalFormat df = new DecimalFormat("#.00");
String formattedNumber = df.format(number);
System.out.println(formattedNumber);
}
}
```
这段代码将输出 "123.46",保留了两位小数。你可以根据需要调整代码中的number变量的值来测试不同的浮点数。
相关问题
Java浮点数保留一位小数
你可以使用Java中的DecimalFormat类来保留浮点数的一位小数。以下是示例代码:
```
double num = 3.1415926;
DecimalFormat df = new DecimalFormat("#.0");
String formattedNum = df.format(num);
System.out.println(formattedNum);
```
输出结果为:3.1
在这个例子中,我们使用了DecimalFormat类的构造函数来指定格式化模式,"#.0"表示保留一位小数。然后,我们将浮点数num传递给format()方法,并将结果存储在一个字符串formattedNum中。最后,我们使用System.out.println()方法来打印formattedNum的值。
java将浮点数保留两位小数
可以使用DecimalFormat类来将浮点数保留两位小数,示例代码如下:
```
double num = 3.1415926;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(num));
```
输出结果为:3.14
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)