0

Title says it all. I get NumberFormatException for obvious reason. I want to input double values to my JTextFields with using comma instead of a dot as the decimal separator since I'm north European.

public void actionPerformed(ActionEvent event2) {

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

    double firstW = Double.parseDouble(firstWeight.getText());
    double secondW = Double.parseDouble(secondWeight.getText());

    double outcome = (firstW - secondW);

    nf.setMaximumFractionDigits(2);
    JLabel result = new JLabel();
    result.setText(nf.format(outcome) +" kg" );

    add(result);
    setVisible(true);

}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Steve Waters
  • 3,348
  • 9
  • 54
  • 94
  • 1
    Unless I missed something, I don't see anything in the JTextField class that does any analysis of the text that the user enters. In particular, I don't think JTextField tries to convert text to numbers. So you must be using a method in some other class. Please clarify how you're doing the conversion, and probably show the code that is supposed to produce the `double` value. – ajb Oct 22 '13 at 15:03
  • Added some code to the question. The result however, is shown in the correct, german form with comma. – Steve Waters Oct 22 '13 at 15:10
  • possible duplicate of [best way to parseDouble with comma as decimal separator?](http://stackoverflow.com/questions/4323599/best-way-to-parsedouble-with-comma-as-decimal-separator) – Mike G Oct 22 '13 at 15:14
  • @mikeTheLiar I couldn't implement that solution to my situation when using JTextField and JLabel. – Steve Waters Oct 22 '13 at 15:16
  • 1
    Why aren’t you just using `new JFormattedTextField(nf)`? – Holger Oct 22 '13 at 15:22
  • Your code sets `nf` to a `NumberFormat` object that specifies German, but you don't use `nf` to parse the input, so `Double.parseDouble` has no way to know that it's supposed to parse in German format. Could that be the problem? – ajb Oct 22 '13 at 15:26

3 Answers3

2

If you have a NumberFormat you already have all you need. Just use NumberFormat.parse instead of Double.parse. But it’s even easier when you use a JFormattedTextField (guess what it does from the class name. Pass the desired NumberFormat to the constructor, i.e. new JFormattedTextField(nf). The JFormattedTextField has a getValue method which returns the last valid edit, in case of your NumberFormat it will be a Number.

Know your libraries

Holger
  • 285,553
  • 42
  • 434
  • 765
0

you can replace the comma with dot when you press the button:

String text=textfield.getText().replace(",",".");

and then you can use the text variable, not the textfield.getText();

A-SM
  • 882
  • 2
  • 6
  • 18
-1

Iterate through text field when submitting and if comma occurs replace with decimal. After the loop convert string to double