java 如何格式化 字符串
时间: 2024-09-29 07:11:21 浏览: 70
在Java中,格式化字符串通常使用`String.format()`方法。这个方法允许您以一种预定义的模式替换占位符,从而创建具有自定义布局的字符串。以下是一些基本示例:
1. **基本数字格式**:
```java
String formattedNum = String.format("%d", 123456); // 输出 "123456"
```
2. **带千分位分隔的大数**:
```java
String formattedLargeNum = String.format("%,d", 1000000); // 输出 "1,000,000"
```
3. **浮点数和精度控制**:
```java
double num = 199.53;
String formattedFloat = String.format("%.2f", num); // 输出 "199.53"
```
4. **日期和时间格式**:
```java
Date date = new Date();
String formattedDate = String.format("%b %d, %Y", date.getMonth(), date.getDate(), date.getFullYear()); // 格式如 "Jan 15, 2023"
```
这些只是基本示例,`String.format()`方法支持更复杂的模式,包括百分比、百分率、货币符号等。要了解更多详情,请查阅官方文档[^2]。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![text/plain](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![java](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![text/x-java](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)