java - Parse double from JFormattedTextField -



java - Parse double from JFormattedTextField -

i've got bug or something. have method saves article, this:

class savearticlelistener implements actionlistener { //.... string s = textarticleprice.gettext().replace(',','.').replaceall("\\s",""); double cost = double.parsedouble(s); //.... }

where textarticleprice jformattedtextfield configured like:

numberformat priceformat = numberformat.getnumberinstance(); priceformat.setmaximumfractiondigits(2); priceformat.setminimumfractiondigits(2); textarticleprice = new jformattedtextfield(priceformat); textarticleprice.setcolumns(10);

and in parsedouble method i'm getting every time:

java.lang.numberformatexception: input string: "123 456 789.00"

so replace works dot, not whitespace... why?

you'd improve off using numberformat parse string. maintain reference priceformat, , use

double cost = priceformat.parse(textarticleprice.gettext()).doublevalue();

the formatter that's beingness used display number same 1 used turn double know it's going parsing in compatible way.

best of is

double cost = ((number) textarticleprice.getvalue()).doublevalue();

which should work without need conversion if you've set jformattedtextfield properly. (the getvalue() phone call returns object, need cast it. might homecoming double or long, depending on what's in text field, safe way double out of treat number, supertype of both, , invoke .doublevalue() method.)

writing converts can parsed double.parsedouble() not right way go because it's fragile if formatting of text field changes later on.

java regex swing jformattedtextfield

Comments

Popular posts from this blog

c - Compilation of a code: unkown type name string -

java - Bypassing "final local variable defined in an enclosing type" -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -