commons-issues mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Marco Janc (JIRA)" <>
Subject [jira] [Created] (LANG-1109) Number percentage formatting with fractional digits
Date Fri, 03 Apr 2015 18:27:52 GMT
Marco Janc created LANG-1109:

             Summary: Number percentage formatting with fractional digits
                 Key: LANG-1109
             Project: Commons Lang
          Issue Type: New Feature
          Components: lang.*
            Reporter: Marco Janc

Java built-in number formatter does formats Number locale aware with fractional digits defined
by the defined scale of the Number, aswell the required precision (trims trailing zeros).

For some reason Java's built-in percentage number formatter does not formats fractional digits.
So i wrote a function which has same behavior as the Java built-in number formatter but with
percentage formatting.

	 * Formats the given Number as percentage with necessary precision.
	 * This serves as a workaround for {@link NumberFormat#getPercentInstance()} which does not
renders fractional
	 * digits.
	 * @param number
	 * @param locale
	 * @return
	public static String formatPercentFraction(final Number number, final Locale locale)
		if (number == null)
			return null;

		// get string representation with dot
		final String strNumber = NumberFormat.getNumberInstance(Locale.US).format(number.doubleValue());
		// create exact BigDecimal and convert to get scale
		final BigDecimal dNumber = new BigDecimal(strNumber).multiply(new BigDecimal(100));

		final NumberFormat percentScaleFormat = NumberFormat.getPercentInstance(locale);
		percentScaleFormat.setMaximumFractionDigits(Math.max(0, dNumber.scale()));

		// convert back for locale percent formatter
		return percentScaleFormat.format(dNumber.multiply(new BigDecimal(0.01)));

I also unit tested it with many inputs.

This message was sent by Atlassian JIRA

View raw message