2014-10-08 23 views
12

我試圖爲一個字符串(14 123)解析到一個長在Java中使用瑞典語言環境中使用此代碼:解析字符串龍使用指定的區域設置(SV)和NumberFormat的

String longString = "14 123" 
NumberFormat swedishNumberFormat = NumberFormat.getInstance(new Locale("sv")); 
System.out.println(swedishNumberFormat.parse(longString).longValue()); 

此代碼的輸出是14(應該是14123)。根據this question,我嘗試了sv和sv_SE語言環境,但是這次在兩種情況下結果都是相同的。

根據http://www.localeplanet.com/java/sv/index.htmlhttp://www.localeplanet.com/java/sv-SE/index.html分組分離器在兩種情況下是一個空間()那麼,爲什麼串地龍解析不處理,該語言環境,存儲爲字符串格式正確的雙重價值?

+0

因此,在Java的瑞典語言環境中的錯誤? – 2014-10-08 11:08:58

+3

對我來說,下面的這個問題和答案比標記爲相關的問題要好。我不認爲這個問題應該關閉。 – Jayan 2014-10-08 11:47:25

回答

12

瑞典人也是法國人,需要努力。不間斷的空間。

longString = longString.replace(' ', '\u00a0'); 

繁瑣。

+0

現在我明白了:) – GameDroids 2014-10-08 11:40:05

+1

@GameDroids是一個完全誤導性的設計決定,使用一個非破壞空間作爲分組分隔符。也許他們想防止在格式生成的數字上發生分詞。 – 2014-10-08 11:51:20

0

您可以試試

解析該字符串並手動設置DecimalFormat。構建它,配置setGroupingUsed(true),setDecimalSymbols用你自己的DecimalFormatSymbols

DecimalFormat df=new DecimalFormat(); 
df.setGroupingSize(3); 
df.setGroupingUsed(true); 
DecimalFormatSymbols newSymbols=new DecimalFormatSymbols(); 
newSymbols.setGroupingSeparator(' '); 
df.setDecimalFormatSymbols(newSymbols); 
df.parse(longString) 

第二個選項是調試你的代碼,參見swedishNumberFormat實例。檢查字段groupingSize,decimalFormatSymbols.groupingSeparators。

0

this post所示,您需要手動將空白區設置爲分隔符。

try { 
     String longString = "14 123";    
     DecimalFormat decimalFormat = new DecimalFormat(); // instead of NumberFormat, use DecimalFormat 
     DecimalFormatSymbols symbols = new DecimalFormatSymbols(new Locale("sv", "SE")); 
     symbols.setGroupingSeparator(' '); // set the whitespace manually as grouping seperator 
     decimalFormat.setDecimalFormatSymbols(symbols);   
     System.out.println(svSE.parse(longString)); 
    } catch (ParseException ex) { 
     Logger.getLogger(Playground.class.getName()).log(Level.SEVERE, null, ex); 
    } 

    //> output is 14123 

說實話我有點困惑,但我認爲問題是,你需要格式化字符串(顯然不是每個空格是這裏的相同)

try { 
     long testNumber = 123987l; 
     NumberFormat swedishNumberFormat = NumberFormat.getInstance(new Locale("sv")); 

     //here I format the number into a String 
     String formatedString = swedishNumberFormat.format(testNumber); 
     System.out.println(formatedString); // result: "123 987" 

     // when parsing the formated String back into a number 
     System.out.println(swedishNumberFormat.parse(formatedString)); // result: "123987" 

     // but when parsing a non formated string like this one 
     System.out.println(swedishNumberFormat.parse("123 987")); // result "123" 
} catch (ParseException ex) { 
     Logger.getLogger(Playground.class.getName()).log(Level.SEVERE, null, ex); 
} 

請糾正我,如果我在這裏錯了,或我的例子沒有工作。我不知道爲什麼它做這樣的事情,但爲了避免混淆像上面這樣的情況,您可能需要手動設置分隔符。

編輯

如喬普埃根在他的answer規定的字符串需要使用硬,不間斷空格('\u00a0'),而不是一個簡單的空白。這就是爲什麼我的例子在最後一行返回「123」的原因(我只使用普通的空格)。

相關問題