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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With