2015-10-06 40 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 

希望这有助于。