問題:Double.parseDouble("37,78584") 拋出 NumberFormatException。原因:字串使用**逗號作為小數點分隔符**(法文/德文/歐洲格式),而非英文預設的點號。
String s = "37,78584";
NumberFormat format = NumberFormat.getNumberInstance(Locale.FRENCH); // 或 Locale.GERMAN, Locale.ITALY 等
Number number = format.parse(s);
double d = number.doubleValue(); // 37.78584
System.out.println(d);
| 類別/方法 | 用途 |
|---|---|
NumberFormat.getNumberInstance(Locale) | 取得指定地區的數字格式化器(含分隔符規則) |
format.parse(String) | 解析字串為 Number 物件 |
number.doubleValue() / intValue() / longValue() | 轉為基本型別 |
Locale.FRENCH, Locale.GERMAN, Locale.ITALY, Locale.KOREA 等 | 預設使用逗號小數點的地區 |
public static Double parseLocalizedDouble(String s, Locale locale) {
if (s == null || s.trim().isEmpty()) return null;
try {
NumberFormat format = NumberFormat.getNumberInstance(locale);
Number number = format.parse(s.trim());
return number.doubleValue();
} catch (ParseException e) {
return null;
}
}
// 使用
Double d1 = parseLocalizedDouble("37,78584", Locale.FRENCH); // 37.78584
Double d2 = parseLocalizedDouble("1.234,56", Locale.GERMAN); // 1234.56 (德文千分位用點)
Double d3 = parseLocalizedDouble("1,234.56", Locale.US); // 1234.56 (美式)
// 貨幣格式
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.FRENCH);
Number price = currencyFormat.parse("37,78 €"); // 37.78
// 百分比格式
NumberFormat percentFormat = NumberFormat.getPercentInstance(Locale.FRENCH);
Number rate = percentFormat.parse("50,5 %"); // 0.505
| Locale | 小數點 | 千分位 | 範例 |
|---|---|---|---|
| US / UK | . | , | 1,234.56 |
| FRENCH / GERMAN / ITALY / SPAIN / KOREA | , | . | 1.234,56 |
| CHINESE | . | , | 1,234.56 |
| JAPAN | . | , | 1,234.56 |
Locale.getDefault()(使用者可隨時更改系統語言)。ParseException 外洩。掌握 NumberFormat + Locale,輕鬆解決全球化數字解析難題。