David
David

Reputation: 13

String to Double Java error

I'm having some problems in the moment of parsing String to Doubles, with Spring and Java. This is not totally related to Spring, but it may put you in situation.

I had a CustomNumberEditor, for parsing easily Strings to Doubles. java.text.DecimalFormat was used as the decimal format for parsing double to string. However, when you do numberFormat.parse(stringDouble) if the string starts with numbers, and follow with letters, the value returned is the numbers. i.e. 12a is parsed to 12. For me this is clearly and error, and I would like to solve this easily.

I imagine this should be implemented in some other kind of numberFormat, or attributes or something, but I could not find it. Any ideas?

Upvotes: 1

Views: 4266

Answers (3)

love_me_some_linux
love_me_some_linux

Reputation: 2741

try{
    double d = Double.parseDouble("12abc");
}
catch(NumberFormatException nfe){
    System.out.println("The string is not formatted correctly");
    //do something here if the string is bad

}

As someone said above, use Double.parseDouble(String s). It will throw an exception if the string is not formatted properly. Then you just wrap that in a try-catch statement and do whatever it is you want your program to do in the event that the input is improperly formatted.

Upvotes: 1

Thomas
Thomas

Reputation: 88707

The parse(...) method won't consume all the text and thus would allow "numbers" like 12a etc. (this might also be a currency like 12USD).

Your CustomNumberEditor might, however, just apply a number only pattern to String#matches(...) in order to check the string only contains a number before parsing it - something like ^-?\d+\.?\d*$ (String must only contain digits, a minus sign and a separator) . You should note however, that this is locale dependent and not as flexible as the decimal format pattern.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

You should use the version of the parse method taking a ParsePosition as argument. Once the parsing is done, the index of the position is updated to the index after the last character used. You can thus check that this index is equal to the length of the string. If it's not, then it means that the whole string has not been used to produce the returned number.

Upvotes: 1

Related Questions