Some Java Guy Some Java Guy -4 years ago 91
Java Question

Creating a Util class

I have created a currency fomatter class. I want this to be a util class and could be used by other applications.
Now I am just taking a string, instead I want it to be set by the application importing my


public class CurrencyUtil{
public BigDecimal currencyUtil(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
BigDecimal amount = new BigDecimal("123456789.99"); //Instead I want the amount to be set by the application.
ThemeDisplay themeDisplay =
Locale locale = themeDisplay.getLocale();

NumberFormat canadaFrench = NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH);
NumberFormat canadaEnglish = NumberFormat.getCurrencyInstance(Locale.CANADA);
BigDecimal amount = new BigDecimal("123456789.99");
DecimalFormatSymbols symbols = ((DecimalFormat) canadaFrench).getDecimalFormatSymbols();
((DecimalFormat) canadaFrench).setDecimalFormatSymbols(symbols);

//Need to have a return type which would return the formats
return amount;

Let other application which calls this util class be

import com.mypackage.CurrencyUtil;
public int handleCurrency(RenderRequest request, RenderResponse response) {
String billAmount = "123456.99";
CurrencyUtil CU = new currencyUtil();
//Need to call that util class and set this billAmount to BigDecimal amount in util class.
//Then it should return both the formats or the format I call in the application.
System.out.println(canadaEnglish.format(billAmount); //something like this

What changes I make?

Answer Source

You need to create an object of CurrencyUtil class.

CurrencyUtil CU = new CurrencyUtil();
//To call a method,
BigDecimal value=CU.currencyUtil(request,response);

I suggest currenyUtil method should be static and it takes three parameters.

public class CurrencyUtil
  public static BigDecimal currencyUtil(
                RenderRequest renderRequest, 
                RenderResponse renderResponse,
                String amountStr) throws IOException, PortletException 
       BigDecimal amount = new BigDecimal(amountStr); 

and you may call it,

 BigDecimal value=CurrencyUtil.currencyUtil(request,response,billAmount);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download