Format and parse a percent

Problem:

You want to format and parse percent values.

Solution:

The Java NumberFormat class makes it easy to create a localized format for a percent value.  Simply pass the locale when retrieving your instance.  The format will see 1 as 100% and .1 as 10%.

 

To format and parse a percent value for Brazillian Portuguese:

//Get a locale.  In this case Portuguese in Brazil
ULocale pt = new ULocale("pt_BR");
//Get an instance of a percent formatter
NumberFormat nf = NumberFormat.getPercentInstance(pt);
//format and output.  1 == 100% and .5 = 50%
String f = nf.format(.78);
System.out.println(f);
//Parse the value.  We must handle the potential ParseException
try {
    System.out.println(nf.parse("78%"));
} catch (ParseException e) {
    e.printStackTrace();
}

 


The output:

78%
0.78