Feb 19

The NumberFormat and DecimalFormat classes provide support for parsing and formatting values.

They are also locale sensitive, which means they adjust the formatting and parsing rules according to the locale or region of interest.

For example in France they use a comma as a decimal separator so 5,48 is the same as 5.48 in the USA.

NumberFormat format = 
   NumberFormat.getInstance(Locale.FRANCE);
Object value = format.parse("5,48");

written by objects \\ tags: , , , , ,

Feb 19

The NumberFormat and DecimalFormat classes provide support for parsing and formatting currency values.

For example to parse a string containing a money value in the default locale you can use the following.

   NumberFormat format = NumberFormat.getCurrencyInstance();
   Object value = format.parse("$5.45");

written by objects \\ tags: , , , , ,

Dec 14

When you need to format a number as a percent you can use the ‘%’ symbol in your DecimalFormat string. The static helper method getPercentInstance() can also be used if you don’t need complete control over the format string.

When the % symbol is used the value is first multiplied by 100 before applying the format string. So 0.123 would become 12.3%.


NumberFormat format1 = new DecimalFormat("##.####%");
NumberFormat format2 = NumberFormat.getPercentInstance();

String formatted1 = format1.format(value);
String formatted2 = format2.format(value);

written by objects \\ tags: , , , , , ,