2017-10-29 160 views
0

我使用的語言環境(語言代碼,COUNTRYCODE)構造一個BigDecimal貨幣值轉換爲語言環境特定貨幣格式來設置特定貨幣字符串所示的代碼下面格式化的BigDecimal使用地點(語言代碼,COUNTRYCODE)

public static String formatCurrency(BigDecimal amount, String languageCode, String countryCode) { 

    Format format = NumberFormat.getCurrencyInstance(new Locale(languageCode, countryCode)); 
    String formattedAmount = format.format(amount); 
    logger.debug("Orginal Amount {} and Formatted Amount {}", amount, formattedAmount); 
    return formattedAmount; 
} 

現在按優秀資源在Oracle Docs

運行環境沒有任何要求,所有的語言環境可以由各個地區敏感的類同樣支持。每個語言環境敏感的類對一組語言環境實現自己的支持,並且該集合可以不同於每個類。例如,數字格式類可以支持與日期格式類不同的一組語言環境。

由於我的語言代碼和COUNTRYCODE由用戶輸入的,我該如何處理這種情況(或者說如何在NumberFormat.getCurrencyInstance方法處理它),當用戶輸入錯誤的輸入就好說了,語言代碼= DE和COUNTRYCODE =我們。

它是否默認爲某些語言環境?如何處理這種情況。

謝謝。

+1

請問你喜歡[這個答案](https://stackoverflow.com/questions/3684747/how-to-validate-a-locale-in-java)嗎? – artie

+0

是的,看起來像LocaleUtils.isAvailableLocale可以使用。 – HopeKing

回答

0

基於從@artie建議,我使用LocaleUtil.isAvailableLocale檢查是否存在語言環境。如果它是一個無效的區域設置,我將它轉換爲en_US。這在一定程度上解決了這個問題。

但是,它仍然沒有如果的NumberFormat支持區域設置檢查解決的問題。將接受解決此問題的任何其他答案。

public static String formatCurrency(BigDecimal amount, String languageCode, String countryCode) { 

     Locale locale = new Locale(languageCode, countryCode); 
     if (!LocaleUtils.isAvailableLocale(locale)) { 
      locale = new Locale("en", "US"); 
     } 
     Format format = NumberFormat.getCurrencyInstance(locale); 
     String formattedAmount = format.format(amount); 
     logger.debug("Orginal Amount {} and Formatted Amount {}", amount, formattedAmount); 
     return formattedAmount; 
    }