首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 字符串格式化與 Math 類核心方法實戰大全

     編輯:Java 相關知識

本文匯總 `String.format()` 格式化輸出的完整佔位符語法、日期時間格式化、標誌/寬度/精度控制,以及 `Math` 類常用數學運算(冪、圓整、隨機數)、`BigDecimal` 大數運算、`SimpleDateFormat` 身份證解析等實戰代碼片段,可作為開發手冊快速查閱。

一、String.format() 完整佔位符速查表

佔位符說明示例輸出
%s字符串`String.format("I am %s", "John")` → `I am John`
%c字符`String.format("Char: %c", 'X')` → `Char: X`
%b布爾值`String.format("Flag: %b", true)` → `Flag: true`
%d十進制整數`String.format("Num: %d", 42)` → `Num: 42`
%x / %X十六進制整數`String.format("Hex: %x", 255)` → `Hex: ff`
%o八進制整數`String.format("Oct: %o", 64)` → `Oct: 100`
%f浮點數(預設 6 位小數)`String.format("Pi: %f", 3.14159)` → `Pi: 3.141590`
%e / %E科學計數法`String.format("Sci: %e", 12345)` → `Sci: 1.234500e+04`
%g / %G通用浮點(自動選 %f 或 %e)`String.format("Gen: %g", 0.000123)` → `Gen: 1.23e-04`
%h散列碼`String.format("Hash: %h", "abc")` → `Hash: 1537462`
%%輸出 % 字面量`String.format("100%%")` → `100%`
%n平台換行符`String.format("Line1%nLine2")`
%t + 日期後綴日期時間組合(見下表)`String.format("%tF", new Date())` → `2023-07-25`

日期時間後綴(%t + 字母)

後綴含義示例
%tFyyyy-MM-dd(ISO 日期)`2023-07-25`
%tDMM/dd/yy(美式日期)`07/25/23`
%tTHH:mm:ss(24小時制)`14:30:05`
%tRHH:mm(24小時制)`14:30`
%trhh:mm:ss a(12小時制 AM/PM)`02:30:05 PM`
%tY / %ty年 / 年後兩位`2023` / `23`
%tm / %td / %te月/日/日(不補0)`07` / `25` / `25`
%tH / %tI / %tk / %tl時(24/12/24不補0/12不補0)`14` / `02` / `14` / `2`
%tM / %tS / %tL / %tN分/秒/毫秒/納秒`30` / `05` / `123` / `123456789`
%tb / %tB月份縮寫/全稱(需 Locale)`Jul` / `July`
%ta / %tA星期縮寫/全稱`Tue` / `Tuesday`
%tpAM/PM 標記`PM`
%tz / %tZ時區偏移/縮寫`+0800` / `CST`
%ts / %tQ秒/毫秒時間戳`1690266605` / `1690266605123`

格式化標誌、寬度、精度控制

// 標誌
String.format("%+d", 10);       // +10  (正數顯示 +)
String.format("%-10s", "abc");  // "abc       " (左對齊)
String.format("%05d", 42);      // "00042" (前導 0 填充)
String.format("%,d", 1000000);  // "1,000,000" (分組分隔符)
String.format("%(d", -42);      // "(42)" (負數括號)
String.format("%#x", 42);       // "0x2a" (十六進制前綴)
String.format("%#f", 42.0);     // "42.000000" (強制小數點)

// 寬度.精度
String.format("%10.2f", 3.14159); // "      3.14" (寬度10, 2位小數)
String.format("%.2f", 3.14159);   // "3.14" (僅精度)

// 參數索引復用
String.format("%1$d %1$04x %1$#x", 42); // "42 002a 0x2a"
String.format("%2$s %1$d", 42, "Hello"); // "Hello 42"

二、Math 類核心方法實戰

// 冪運算
Math.pow(2, 10);        // 1024.0 (double)
BigDecimal bd = new BigDecimal("2");
bd.pow(10);             // 1024 (精確整數)

// 圓整
Math.ceil(3.14);   // 4.0
Math.floor(3.99);  // 3.0
Math.round(3.5);   // 4 (long)
Math.round(-3.5);  // -3 (注意:-3.5 -> -3, -3.6 -> -4)

// 絕對值、最大最小
Math.abs(-5);           // 5
Math.max(3, 7);         // 7
Math.min(3, 7);         // 3

// 根號、三角、對數
Math.sqrt(2);           // 1.414...
Math.sin(Math.PI/2);    // 1.0
Math.log(10);           // ln(10)
Math.log10(100);        // 2.0

// 隨機數
Math.random();                    // [0.0, 1.0) double
(int)(Math.random() * 100);       // [0, 99]
(int)(Math.random() * 101);       // [0, 100]
(int)(Math.random() * 71 + 30);   // [30, 100]

// Random 類(更靈活)
new Random().nextInt(101);        // [0, 100]
new Random().nextInt(100) + 1;    // [1, 100]

三、SimpleDateFormat 身份證號解析生日與性別

String id = "411123199409203013"; // 18 位
if (id.length() == 18) {
    String birthStr = id.substring(6, 14); // 19940920
    String sex = Integer.parseInt(id.substring(16, 17)) % 2 == 0 ? "女" : "男"; // 第 17 位
    
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    Date birth = sdf.parse(birthStr);
    sdf = new SimpleDateFormat("yyyy年MM月dd日");
    System.out.println("生日: " + sdf.format(birth) + ",性別: " + sex);
    
    // String.format 日期格式化復用
    String msg = String.format("生日: %1$tY年%1$tm月%1$td日,性別: %2$s", birth, sex);
    System.out.println(msg);
}

四、總結

  • `String.format()` 佔位符豐富,掌握 `%s/%d/%f/%tX/%n/標誌/寬度/精度/參數索引` 覆蓋 95% 格式化需求。
  • 日期格式化優先用 `%t` 系列,避免 `SimpleDateFormat` 線程不安全問題。
  • `Math` 類適合簡單科學計算;精確金融/大整數必用 `BigDecimal`/`BigInteger`。
  • 隨機數首選 `Random` 類(可指定種子、線程安全 `ThreadLocalRandom`)。

將本文作為備忘錄,遇到格式化、數學運算需求快速複製調試。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved