创建Util类

时间:2012-01-02 09:44:38

标签: java format return currency

我创建了一个货币fomatter类。我希望它是一个util类,可以被其他应用程序使用。 现在我只是取一个字符串,而不是我希望它由导入我的currencyUtil.jar

的应用程序设置
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 = 
             (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
        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();
        symbols.setGroupingSeparator('.');
        ((DecimalFormat) canadaFrench).setDecimalFormatSymbols(symbols);

    System.out.println(canadaFrench.format(amount));
        System.out.println(canadaEnglish.format(amount));     
    //Need to have a return type which would return the formats
     return amount;
    }
}

让其他调用此util类的应用程序为

 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
}

我做了哪些改变?

2 个答案:

答案 0 :(得分:1)

您需要创建CurrencyUtil类的对象。

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

我建议currenyUtil方法应为static,并且需要三个参数。

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

你可以打电话给它,

 BigDecimal value=CurrencyUtil.currencyUtil(request,response,billAmount);

答案 1 :(得分:0)

根据Joshua Bloch的Effective Java, 第4项:使用私有构造函数强制执行非实例化:

public final class CurrencyUtil {

    // A private constructor
    private CurrencyUtil() {
        throw new AssertionError();
    }

    //Here goes your methods
}
相关问题