Cq5 formatting string to a number with decimal places

How to format from a string to a number, the date coming from a request param. The only thing not covered here is to catch exceptions if the parameter passed was not a number. In all other cases falls back safely.

// e.g ?myStringNum=2.44433 in request URL
String myStringNum= request.getParameter("myStringNum");
if (myStringNum!= null) {
// cast as number first and decode the string if required
    Number formattedNumber=Float.valueOf(URLDecoder.decode(request.getParameter("myStringNum"),"UTF-8"));
// formatting template , to one decimal place
	DecimalFormat df = new DecimalFormat("#.#");
// set the attribute for cq5
     request.setAttribute("formattedNumber",df.format(formattedNumber));
}

//Then in your CQ5 template add
${formattedNumber}

Leave a Reply

Your email address will not be published. Required fields are marked *

*