05:输出保留12位小数的浮点数java
时间: 2023-10-13 10:24:49 浏览: 101
可以使用DecimalFormat类来格式化浮点数并保留12位小数。以下是一个示例代码:
```java
double num = 3.14159265358979323846;
DecimalFormat df = new DecimalFormat("#.############");
String formattedNum = df.format(num);
System.out.println(formattedNum);
```
输出结果为:3.141592653590。可以看到,该浮点数被格式化为保留12位小数的字符串。
相关问题
java浮点数保留2位小数
在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的值。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)