wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Validate Numeric User Input Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Validate Numeric User Input " Watch "Validate Numeric User Input " New topic
Author

Validate Numeric User Input

dave taubler
Ranch Hand

Joined: May 15, 2001
Posts: 132
Hi,

I'm trying to do something that I thought would be common and trivial, but after hours of googling, appears to be neither. Basically, I am simply trying to determine whether a given String represents a valid integer (or decimal, in some cases) for a given locale.

First, I checked simply to see if methods like Integer.parseInt() accept a Locale; they do not. Then, I thought I could retrieve the decimal-separator and group-separator (e.g. a comma--as in 1,000--in the US) from either the Locale or the NumberFormat object and do my own validation of the String, but I cannot retrieve that information either. So finally I decided to try a brute force approach just try to parse the String and if it works, the String is valid, and if an Exception is thrown, it is not valid:



But it turns out that you can pass pretty much any String in, and the NumberFormat will force it into a number. Seriously, "1asdsad" successfully converts to 1.

My last option, I guess, is to simply parse the String and validate that every character is either a number, or '.', '\'', ' ', or ','. But that hardly seems accurate, and would cause a lot of false negatives. So I think I must be missing something. What I'm trying to do has got to be commonplace, but I can't find any examples anywhere.

Does anyone know of a proper approach?

Thanks in advance.


Dave Taubler<br />Specializing in <a href="http://taubler.com/articles/" target="_blank" rel="nofollow">Java and Web Development</a>
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi Dave,

You're really close. You can use the version of NumberFormat.parse() which takes a ParsePosition as the second argument. When parse() returns, check to see if theParsePosition.getIndex() == theString.length(); if it is, the parse accepted all the characters.


[Jess in Action][AskingGoodQuestions]
dave taubler
Ranch Hand

Joined: May 15, 2001
Posts: 132
Ernest,

Thanks so much for your response. I did a quick check, and it seems indeed this will solve my issue.

Best regards,
Dave
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Validate Numeric User Input