I'm trying to internationalize my app on Android. I know that in Europe as well as other parts of the world decimals and numbers are represented in a different way than the U.S.
I'm trying to use NumberFormat to help me change string inputs that represent decimals in Europe. So, for example:
I have code that nearly works to perfection but I'm missing something: I don't want to use the method String.format. I want to use NumberFormat.
NumberFormat nformat = NumberFormat.getInstance(Locale.US);
nformat.setMaximumFractionDigits(2);
nformat.setMaximumFractionDigits(2);
String user_string = "8,747";
try{
Number my_number = nformat.parse(user_string);
String result = nformat.format(my_number);
System.out.println("look at result: " + result); //this prints: 8,747.00 NOT 8.75
}catch(Exception exception){
}
How can I make NumberFormat to print 8.75 AND not 8,747.00 . Also ,I can use a replace OR replaceAll call on the user_string BUT I don't want to use extra computations. How can NumberFormat handle this problem?
thanks
Before answering your question I want to tell you not to swallow exception. An empty catch block is a bad no-no. Edit: When the exception happens, you will have no idea what went wrong in your program. It’s like coding blind-folded. The short article linked to at the bottom explains in more details how this practice defeats the purposes of exceptions.
For converting from one string format to another string format you need two formatters, one for parsing and one for formatting.
NumberFormat europeanInputFormat = NumberFormat.getInstance(Locale.GERMAN);
NumberFormat nformat = NumberFormat.getInstance(Locale.US);
nformat.setMaximumFractionDigits(2);
String user_string = "8,747";
try {
Number my_number = europeanInputFormat.parse(user_string);
String result = nformat.format(my_number);
System.out.println("look at result: " + result); // this prints: 8.75
} catch (ParseException | IllegalArgumentException e) {
e.printStackTrace();
}
Output:
look at result: 8.75
Not all European countries use the same format. I had first used Locale.FRENCH
. That didn’t work because the French format uses space rather than dot as thousands separator.
Wikipedia article on Error hiding, error swallowing or exception swallowing