java中的format如何使用

29次阅读
没有评论

共计 779 个字符,预计需要花费 2 分钟才能阅读完成。

在 Java 中,可以使用 String.format() 方法来格式化字符串。该方法使用格式字符串和可选的参数,返回一个格式化后的字符串。
以下是使用 String.format() 方法的一些示例:

  1. 格式化整数:
int num = 123456;
String formatted = String.format("%d", num);
System.out.println(formatted);   // 输出: 123456
  1. 格式化浮点数:
double num = 3.14159;
String formatted = String.format("%.2f", num);
System.out.println(formatted);   // 输出: 3.14
  1. 格式化日期:
import java.util.Date;
Date now = new Date();
String formatted = String.format("%tF", now);
System.out.println(formatted);   // 输出: 2022-01-01
  1. 格式化字符串:
String name = "John";
int age = 30;
String formatted = String.format("My name is %s and I'm %d years old.", name, age);
System.out.println(formatted);   // 输出: My name is John and I'm 30 years old.

格式字符串中的占位符可以使用不同的格式说明符来指定所需的格式,例如 %d 表示整数,%.2f表示带两位小数的浮点数,%s表示字符串等。
此外,还有其他格式说明符可供选择,例如 %tF 表示完整的日期格式,%tH:%tM:%tS表示小时、分钟和秒等。
希望以上示例能帮助您了解如何使用 String.format() 方法进行字符串格式化。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-20发表,共计779字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)