2012-09-10 22 views
0

我有這樣的代碼:數字格式()不給預期的結果

public double stringToDouble(String s) { 

     NumberFormat nf = NumberFormat.getInstance(Locale.getDefault()); 

    try { 

     return nf.parse(s).doubleValue(); 
    } catch (java.text.ParseException e) { 
     return 0.0; 
    } 
} 

其工作正常,但與像一些60.0值它給600.0,我不知道爲什麼,60它給60.0

有什麼建議嗎?在此先感謝

回答

0

OK,答案是使用此代碼:

public double stringToDouble(String s) { 

     NumberFormat nf = NumberFormat.getInstance(Locale.getDefault()); 
    nf.setGroupingUsed(false); 
    ParsePosition parsePosition = new ParsePosition(0); 
    Number n = nf.parse(s, parsePosition); 
    if (n == null || parsePosition.getErrorIndex() >= 0 || parsePosition.getIndex() < s.length()) 
    { 
     /* not a valid number */ 
    } 
    return n.doubleValue(); 
} 

使用這種替代Double.parseDouble();

0

這是因爲你的機器(JVM)的默認語言環境被解釋爲點一組字符(3位分組像1.000.000,00)和最有可能的小數點分隔符是逗號。

我在我的機器上使用默認英國的語言環境 運行你的代碼和

System.out.println(stringToDouble("60.0")); System.out.println(stringToDouble("60")); System.out.println(stringToDouble("60,0"));

它打印: 60.060.0600.0

對於便攜別t設置默認但特定的區域設置。