Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自訂語言(俄語、西班牙語)下 String.format("%.2f") 把小数點變成逗號的原因與解法

編輯:關於 Android 程式設計

市場人員回報:把系統語言設為俄語或西班牙語之後,App 內的 double 數值顯示時,小數點變成了逗號。

實測確認,問題出在自訂語言的情境下呼叫 String.format("%.2f", 67.876),輸出的確會變成 67,88。以下把成因與解法完整梳理一次。

一、Android 系統語言的設定路徑

【設定】→【語言與輸入法】→【語言】,在清單中選取對應的語言項即可。

二、問題分析

Locale 類別的預設清單是有限的

java.util.Locale 中預先定義的常數並不多:

/** Locale constant for en_CA. */
public static final Locale CANADA = new Locale(true, "en", "CA");

/** Locale constant for fr_CA. */
public static final Locale CANADA_FRENCH = new Locale(true, "fr", "CA");

/** Locale constant for zh_CN. */
public static final Locale CHINA = new Locale(true, "zh", "CN");

/** Locale constant for zh. */
public static final Locale CHINESE = new Locale(true, "zh", "");

/** Locale constant for en. */
public static final Locale ENGLISH = new Locale(true, "en", "");

俄語、西班牙語都不在其中。而真正能建立自訂 Locale 的那個建構子,是 private 的:

/**
 * There's a circular dependency between toLowerCase/toUpperCase and
 * Locale.US. Work around this by avoiding these methods when constructing
 * the built-in locales.
 *
 * @param unused required for this constructor to have a unique signature
 */
private Locale(boolean unused, String lowerCaseLanguageCode, String upperCaseCountryCode) {
    this.languageCode = lowerCaseLanguageCode;
    this.countryCode = upperCaseCountryCode;
    this.variantCode = "";
}

所以外部唯一能用的,是這個公開建構子:

/**
 * Constructs a new {@code Locale} using the specified language, country,
 * and variant codes.
 */
public Locale(String language, String country, String variant) {
    if (language == null || country == null || variant == null) {
        throw new NullPointerException();
    }
    if (language.isEmpty() && country.isEmpty()) {
        languageCode = "";
        countryCode = "";
        variantCode = variant;
        return;
    }
    languageCode = language.toLowerCase(Locale.US);

    // 把新語言碼映射回舊碼,才能命中正確的資源包
    if (languageCode.equals("he")) {
        languageCode = "iw";
    } else if (languageCode.equals("id")) {
        languageCode = "in";
    } else if (languageCode.equals("yi")) {
        languageCode = "ji";
    }

    countryCode = country.toUpperCase(Locale.US);
    variantCode = variant;
}

專案裡於是這樣自建語言並套用:

private static final Locale Locale_Russia = new Locale("RUS", "ru", "");
private static final Locale Locale_Spanish = new Locale("ES", "es", "");

public static void setApplicationLauguageType(Context context, int type) {
    if (context == null) return;

    Resources resources = context.getResources();       // 取得 res 資源物件
    Configuration config = resources.getConfiguration(); // 取得設定物件
    DisplayMetrics dm = resources.getDisplayMetrics();   // 取得螢幕參數

    switch (type) {
        case 0: config.locale = Locale.getDefault();        break;
        case 1: config.locale = Locale.SIMPLIFIED_CHINESE;  break;
        case 2: config.locale = Locale.ENGLISH;             break;
        case 3: config.locale = Locale_Russia;              break;
        case 4: config.locale = Locale_Spanish;             break;
        default: config.locale = Locale.getDefault();       break;
    }
    resources.updateConfiguration(config, dm);
}

順帶一提:這裡兩個 Locale 的參數順序寫反了。建構子簽名是 Locale(language, country, variant),所以俄語應該是 new Locale("ru", "RU", ""),西班牙語則是 new Locale("es", "ES", "")。寫成 ("RUS", "ru", "") 會讓語言碼變成 rus、國家碼變成 RU,雖然勉強能跑,但不符合規範,某些 API 上會出現在找不到資源的狀況。

String.format 預設使用系統 Locale

日常最常寫的:

String strResult = String.format("%0.2f", 543.6356);

它其實是這個方法的簡寫:

/**
 * Returns a localized formatted string, using the supplied format and
 * arguments, using the user's default locale.
 *
 * If you're formatting a string other than for human consumption, you
 * should use the {@code format(Locale, String, Object...)} overload and
 * supply {@code Locale.US}. See "Be wary of the default locale".
 */
public static String format(String format, Object... args) {
    return format(Locale.getDefault(), format, args);
}

注意官方文件裡那句警告:Be wary of the default locale。這個多傳出去的 Locale.getDefault(),正是問題的起點——它會取用系統當前語言設定,而俄語、西班牙語等語系慣例上用逗號當小數分隔符。

接著它走進:

/**
 * Returns a formatted string, using the supplied format and arguments,
 * localized to the given locale.
 *
 * @param locale the locale to apply; {@code null} value means no localization.
 */
public static String format(Locale locale, String format, Object... args) {
    if (format == null) {
        throw new NullPointerException("format == null");
    }
    int bufferSize = format.length() + (args == null ? 0 : args.length * 10);
    Formatter f = new Formatter(new StringBuilder(bufferSize), locale);
    return f.format(format, args).toString();
}

關鍵是最後那行:Formatter 帶著 locale 走,而 Formatter 在格式化浮點數時,會採用該 locale 的 DecimalFormatSymbols。於是:

double dValue = 360.672;
String strValue = String.format("%.2f", dValue);
// 中文、英文環境 → "360.67"
// 俄語、西班牙語環境 → "360,67"

如果用的是 Locale 類別裡有定義的語言(中文、英文),不會遇到這問題;一旦換成自建語言,就現形了。

三、解法

既然預設會取系統語言,那就自己明確傳入:

double dValue = 360.672;
String strValue = String.format(Locale.ENGLISH, "%.2f", dValue);

理由很直白:機器的資料格式全世界通用,小數點就是小數點。凡是要給後端、要寫進檔案、要再做解析的字串,一律用 Locale.ENGLISH(或 Locale.US)格式化。只有最終要呈現在畫面上給人看的數字,才該跟隨系統語言。

混用字串與數值的場景要特別留意:

// 原本這樣寫,兩段都会被当成英文格式化,中文翻譯就失效了
String strResult = String.format("%s:%.3f\r\n",
        getString(R.string.IteInfoCoorType), 654.76);

正確做法是拆成兩步:文字部分交給系統 Locale 走資源檔,數值部分固定用 Locale.ENGLISH,最後再拼接:

String label = getString(R.string.IteInfoCoorType);           // 跟隨系統語言
String value = String.format(Locale.ENGLISH, "%.3f", 654.76); // 固定小數點
String strResult = label + ":" + value + "\r\n";

四、這算不算 SDK 的 bug

嚴格說不算。這是 Formatter 依設計 localization 的結果,官方文件也早已警示。真正的問題在我們這邊:把「給機器讀的資料」和「給人看的文字」用了同一條格式化路徑。

測試環境為 JDK 1.7 搭配 Android SDK 4.2。這個坑不限於俄語與西班牙語,阿拉伯語、法語等以小數點為千分位的語系同樣會中,只要專案有做多語言,就值得全專案掃一遍 String.format 的呼叫點。

// 有問題
String.format("%.2f", dValue);

// 正確
String.format(Locale.ENGLISH, "%.2f", dValue);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved