Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you format a fractional percentage with java.text.MessageFormat

My percentages get truncated by the default java.text.MessageFormat function, how do you format a percentage without losing precision?

Example:

String expectedResult = "12.5%"; double fraction = 0.125;  String actualResult = MessageFormat.format("{0,number,percent}", fraction); assert expectedResult.equals(actualResult) : actualResult +" should be formatted as "+expectedResult; 
like image 972
Lorin Avatar asked Mar 30 '09 17:03

Lorin


1 Answers

I think the proper way to do it is the following:

NumberFormat percentFormat = NumberFormat.getPercentInstance(); percentFormat.setMaximumFractionDigits(1); String result = percentFormat.format(0.125); 

It also takes internalization into account. For example on my machine with hungarian locale I got "12,5%" as expected. Initializing percentFormat as NumberFormat.getPercentInstance(Locale.US) gives "12.5%" of course.

like image 136
Chei Avatar answered Oct 09 '22 02:10

Chei