2015-10-06 49 views
0

我正在製作一個簡單的計算器,目前正試圖解決非整數問題。試圖從文本字段中讀取格式化的雙精度值

有一個文本字段displayField顯示結果和操作員按鈕以及一個相等的按鈕。

剛剛得到它的工作,雙重結果只顯示小數位,如果有任何,但我不能得到結果回計算。

public class FXMLDocumentController implements Initializable { 

private String operator; 
double oldValue; 
double newValue = 0; 
NumberFormat nf = new DecimalFormat("##.###"); 

@FXML 
private TextField displayField; 

@Override 
public void initialize(URL url, ResourceBundle rb) { 
    // TODO 
} 

@FXML 
private void handleDigitAction(ActionEvent event) { 
    String digit = ((Button) event.getSource()).getText(); 
    String oldText = displayField.getText(); 
    String newText = oldText + digit; 
    displayField.setText(newText); 
} 

@FXML 
private void handleOperator(ActionEvent event) { 
    oldValue = Double.parseDouble(displayField.getText()); 
    displayField.setText(""); 
    operator = ((Button) event.getSource()).getText(); 
} 

@FXML 
private void handleEqualAction(ActionEvent event) { 

    switch (operator) { 
     case "+": 
      newValue = oldValue + Double.parseDouble(displayField.getText()); 
      break; 
     case "-": 
      newValue = oldValue - Double.parseDouble(displayField.getText()); 
      break; 
     case "*": 
      newValue = oldValue * Double.parseDouble(displayField.getText()); 
      break; 
     case "/": 
      newValue = oldValue/Double.parseDouble(displayField.getText()); 
      break; 
     default: 
      break; 
    } 

    displayField.setText(String.valueOf(nf.format(newValue))); 
} 

}

的錯誤,當我例如嘗試計算5/2第一,得到的結果2,5,然後點擊操作按鈕時發生。 所以我想我只需要使用一個額外的對象來保存結果或者只是改變我從文本字段中讀取的行(這樣它也適用於這種改變的格式),但我不知道如何。

+0

目前還不清楚你在問什麼。當您第二次點擊操作員按鈕時,什麼值? – ergonaut

回答

1

你能告訴我們你的應用程序運行在哪個區域嗎?

執行

System.out.println(Locale.getDefault()); 
+0

它說我de_DE – Someguy

+0

我看到你找到了一個解決方案。那很棒。這是問題所在,德語區域設置使用與您期望的格式不同的格式。 – user1531914

1

當使用NumberFormatformat()方法(或它的子類DecimalFormat),則恰好在使用任一默認LocaleLocale傳遞的方法中,這取決於過載你使用。因此,您會得到一個格式爲Locale的輸出。

同樣,您應該使用DecimalFormatparse()方法根據相同的規則解析顯示字段。

我希望這將有助於...

傑夫

1

我發現了一個相當「簡單」或骯髒的解決方案,這似乎工作:

NumberFormat nf = new DecimalFormat("##.###", new DecimalFormatSymbols(Locale.US)); 
1

您可能正在使用DecimalFormat類格式化輸出。十進制格式使用默認的Locale,在你的情況下是de_DE。 正如在上面的答案中提到的,您可以使用DecimalFormat類的重載方法以您所需的格式獲取輸出。

E.g.

BigDecimal numerator = new BigDecimal(5); 
BigDecimal denominator = new BigDecimal(2); 

//In current scenario 
    Locale locale = new Locale("de", "DE"); 
    NumberFormat format = DecimalFormat.getInstance(locale); 
    String number = format.format(numerator.divide(denominator)); 
    System.out.println("Parsed value is "+number); 

The output here will be 2,5 

如果更改爲:

Locale localeDefault = new Locale("en", "US"); 
    NumberFormat formatDefault = DecimalFormat.getInstance(localeDefault); 
    String numberVal = formatDefault.format(numerator.divide(denominator)); 
    System.out.println("Parsed value is "+numberVal); 

    Output here will be 2.5 

希望這有助於。