You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@commons.apache.org by "Benedikt Ritter (JIRA)" <ji...@apache.org> on 2015/04/18 20:11:58 UTC
[jira] [Commented] (LANG-1109) Number percentage formatting with
fractional digits
[ https://issues.apache.org/jira/browse/LANG-1109?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=14501505#comment-14501505 ]
Benedikt Ritter commented on LANG-1109:
---------------------------------------
[~djmj] can you please give some example inputs and outputs or even better a JUnit test for this functionality?
> 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
> Fix For: Discussion
>
>
> 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.
> {code:java}
> /**
> * 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)));
> }
> {code}
> I also unit tested it with many inputs.
--
This message was sent by Atlassian JIRA
(v6.3.4#6332)