You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@commons.apache.org by "Marco Janc (JIRA)" <ji...@apache.org> on 2015/04/03 20:27:52 UTC

[jira] [Created] (LANG-1109) Number percentage formatting with fractional digits

Marco Janc created LANG-1109:
--------------------------------

             Summary: Number percentage formatting with fractional digits
                 Key: LANG-1109
                 URL: https://issues.apache.org/jira/browse/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
(v6.3.4#6332)