• Post Reply Bookmark Topic Watch Topic
  • New Topic

Check number format by Locale  RSS feed

 
David Follow
Ranch Hand
Posts: 223
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
imagine you have some type of client (Swing, JSP, CommandLine) that reads
a number value (e.g. 1.234) from the keyboard. "1.234" is represented as a String.
Now, having an international application, in the US the user may enter 1.234
whereas in Europe the user may enter 1,234
How can I make sure that my code can work with both formats equally?
I know there is such thing as Locales but how would I apply them in my case?
Further, how can I guaranty that the user won't enter something like 1.2funny34 or 1,2funny34 ?
I know I will get a NumberFormatException if I try to convert the String to
a double or something else but I still have the problem with "." and ",".
Any smart ideas?
 
David Follow
Ranch Hand
Posts: 223
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe,
your Links show how to format a number but not how it is validated
using the appropriate pattern e.g. 1.23 for USA and 1,23 for Europe
or did I overlook something?
 
Joe Ess
Bartender
Posts: 9441
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe you have to read into it. java.text.NumberFormat is locale sensitive. You can call format() to get a String formatted for the default locale and parse() to change a String into a java.lang.Number instance. parse() will throw a NumberFormatException if the input is not a valid number. If its valid, run it through some logic to see if the value of the Number instance makes sense for your application.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!