How to print numeric attributes with custom separator symbols

by Laura Cigardi
5,157 views Published on Oct 24, 2011
Applies to: All versions
Table of contents

Working with templates allows you to make customization with number patterns. Suppose that you do not want to use the separator symbols for numbers according to the current locale, but you want to use custom character (unusual for separators). You just have to create a custom attribute template that realizes this feature.

This is a template example:


#?delimiters [%, %], [%=, %]

<wr:LayoutParameter label="Decimal Separator" name="decimal-separator" type="string">

Defines the decimal separator to use in the custom format

</wr:LayoutParameter>

<wr:LayoutParameter label="Group Size" name="group-size" type="string" default="3">

Defines the size of number group, which means how many digits have to be displayed before to print the group separator.

</wr:LayoutParameter>

<wr:LayoutParameter label="Group Separator" name="group-separator" type="string">

Defines the group separator to use in the custom format. The group separator is used when you want to group some digits in the value

</wr:LayoutParameter>



[%

setHTMLOutput()

def type = attr["type"]

def subType = attr["subType"]

def typeId = (subType != "") ? subType : type

def pattern = typeId + "Pattern"

def attrProp = getFieldName(getAttributeById(attr["attribute"]))

def mode = attr["mode"]

def decimalSeparator = params["decimal-separator"]

def groupSeparator = params["group-separator"]

def groupSize = params["group-size"]

%]

<c:set var="number" value="${[%= item%].[%=attrProp%]}"/>

<% {

java.util.Locale currentLocale = (java.util.Locale)pageContext.getAttribute("javax.servlet.jsp.jstl.fmt.locale");

java.text.DecimalFormatSymbols unusualSymbols = new java.text.DecimalFormatSymbols(currentLocale);

unusualSymbols.setDecimalSeparator('[%= decimalSeparator %]');

unusualSymbols.setGroupingSeparator('[%=groupSeparator %]');



String pattern = (String) pageContext.getAttribute("[%= pattern %]");

java.text.DecimalFormat weirdFormatter = new java.text.DecimalFormat(pattern, unusualSymbols);

weirdFormatter.setGroupingSize([%= groupSize %]);

Double n = (Double) pageContext.getAttribute("number");

if (n == null) { n = new Double(0); }

String formattedValue = weirdFormatter.format(n.doubleValue());

pageContext.setAttribute("formattedValue",formattedValue);

} %>

<c:out value="${formattedValue}"/>

This template allows you to choose through some Layout Parameters:

  • The decimal separator. This is the separator used between the integer part of the number and the decimal part.
  • The group size. This is the size of a group of digits inside the number.
  • The group separator. This is the separator used between two different groups of digits.

This is a result example: