简体   繁体   中英

Parse double from JFormattedTextField

I've got a bug or something. I have a method that saves an article, like this:

  class SaveArticleListener implements ActionListener {
    //....
    String s = textArticlePrice.getText().replace(',','.').replaceAll("\\s","");
    double price = Double.parseDouble(s);
    //....
}

Where textArticlePrice is a JFormattedTextField which configured like:

NumberFormat priceFormat = NumberFormat.getNumberInstance();
priceFormat.setMaximumFractionDigits(2);
priceFormat.setMinimumFractionDigits(2);
textArticlePrice = new JFormattedTextField(priceFormat);
textArticlePrice.setColumns(10);

And in the parseDouble method I'm getting every time:

java.lang.NumberFormatException: For input string: "123 456 789.00"

So replace works with a dot, but not with whitespace... Why?

You'd be better off using your NumberFormat to parse the String . Keep a reference to priceFormat , and then use

double price = priceFormat.parse(textArticlePrice.getText()).doubleValue();

The formatter that's being used to display the number is the same one then used to turn it back into a double so you know it's going to be parsing it in a compatible way.

Best of all is

double price = ((Number) textArticlePrice.getValue()).doubleValue();

which should work without any need for conversion if you've set your JFormattedTextField up properly. (The getValue() call returns an Object , so you need to cast it. It might return a Double or a Long , depending on what's in the text field, so the safe way to get a double out of it is to treat it as a Number , which is the supertype of both, and invoke its .doubleValue() method.)

Writing something that converts it into something that can be parsed by Double.parseDouble() is really not the right way to go because it's too fragile if the formatting of your text field changes later on.

Regarding your question" why doesn't it work with white spaces". White spaces are chars just like a,l,#,?,¡, but it only recognises ,12345, numbers together as a number, you cant make an int variable 'int number = 1 234; Its the same with parsing. Rather try,

s = s.replace(',','.');
s = s.replace(" ","");
Price = Double.parseDouble(s);

Assuming that '123 456 789.00' is one number.

please comment if this helped.

I did this now, it worked fine

String strNumber = "1 2 3 4 5 6.789";
double DblNumber = Double.parseDouble(strNumber);
System.out.Println(DblNumber);// this displays the number if your IDE has an output window

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM