开发者

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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜