Java number formatting: Locale
The tutor continues about number formatting with Java.
We don’t live in countries any more; rather, we live in the world. Right now, for instance, my family is off in the US. I’m not with them; I stayed home to run the business. In fact, I’m not a traveller.
I learn about the world from print, which is how I recently became aware that number formats vary from country to country. Behold the many faces of 1 139 275.78:
| France | 1 139 275,78 |
| Germany | 1.139.275,78 |
| US, Canada, English | 1,139,275.78 |
| Canada (French) | 1 139 275,78 |
Notice that none of those nation-specific formats is the way I write the number (once again: 1 139 275.78). I was taught that, in Metric, the thousands separators are spaces, not commas. Yet, being in an English-speaking country, I use a decimal point rather than a comma. It’s an interesting mash of formats that I believe scientifically-educated North Americans commonly use:)
Being an international programming language, Java is prepared to accommodate the number formats used in different countries. Java calls a country a locale.
I wrote two earlier posts on Java decimal number formatting here and here. Any Java programmer who is reading this article likely wants the key lines that enable a program to translate a number from one country’s format to another’s. You start with an instance of NumberFormat, setting it with the desired locale:
NumberFormat numform = NumberFormat.getInstance(Locale.COUNTRY)
For example, to get the format used in France:
NumberFormat numform0 = NumberFormat.getInstance(Locale.FRANCE);
Next, you cast the NumberFormat instance into a DecimalFormat object:
DecimalFormat decform0 = (DecimalFormat)numform0;
Finally, you apply the format descriptor string; for example,
decform0.applyPattern(“#,##0.00”);
Now, you can format number num0 to String string0, in the style of France:
string0 = decform0.format(num0);
To use the above code effectively, you’ll need to include the lines
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.util.Locale;
above the class definition.
As far as I’ve read, not necessarily every country has a locale in Java. You can see which ones do here.
HTH:)
Other sources:
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.
Leave a Reply
You must be logged in to post a comment.