Java如何格式化输出小数点后16位
时间: 2023-06-18 11:04:18 浏览: 80
在Java中,可以使用DecimalFormat类来格式化输出小数点后16位。下面是一个示例代码:
```java
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
double num = 3.141592653589793;
DecimalFormat df = new DecimalFormat("#.###############");
System.out.println(df.format(num));
}
}
```
输出结果为:
```
3.141592653589793
```
在DecimalFormat构造函数中,我们使用了字符串 `#.###############` 来表示小数点后最多保留16位,如果小数点后位数不足16位,则会自动补0。
相关问题
java输出取小数点后两位
在Java中,我们可以使用`DecimalFormat`类来格式化输出小数点后两位。例如:
```
double number = 3.1415926;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
System.out.println(decimalFormat.format(number));
```
输出结果为:`3.14`
在上述代码中,我们使用了`DecimalFormat`类创建了一个格式化器对象,使用`#`表示可选的数字位数,使用`0`表示必选的数字位数,`.`表示小数点,`##`表示小数点后最多只保留两位数字。然后将需要格式化的数字传入`format()`方法中,即可输出格式化后的结果。
java浮点数输出默认保留小数点后六位多种方法
在Java中,可以使用多种方法来输出浮点数并保留小数点后六位。以下是几种常用的方法:
1. 使用String.format()方法
```java
double num = 3.1415926;
String str = String.format("%.6f", num);
System.out.println(str);
```
在上面的代码中,我们使用String.format()方法来格式化输出,其中格式化字符串"%.6f"表示输出浮点数并保留小数点后六位。
2. 使用DecimalFormat类
```java
double num = 3.1415926;
DecimalFormat df = new DecimalFormat("#.######");
System.out.println(df.format(num));
```
在上面的代码中,我们使用DecimalFormat类来格式化输出,其中格式化字符串"#.######"表示输出浮点数并保留小数点后六位。
3. 使用BigDecimal类
```java
double num = 3.1415926;
BigDecimal bd = new BigDecimal(num);
System.out.println(bd.setScale(6, BigDecimal.ROUND_HALF_UP));
```
在上面的代码中,我们使用BigDecimal类来格式化输出,其中setScale()方法设置小数点后保留的位数为6,ROUND_HALF_UP表示四舍五入。
无论使用哪种方法,输出结果都是:
```
3.141593
```
可以看到,输出结果保留了小数点后六位数字。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![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)