如何将十进制数格式化为货币。

时间:2012-05-11 02:10:09

标签: java jsp number-formatting

我想使用数字格式在矢量中为产品编写价格。这是我的代码

<%!
        class product
        {
            public String name;
            public int price;
            public String image;

            public product()
            {
            }
        }
    %>
<%
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setCurrencySymbol("$ ");
    dfs.setGroupingSeparator('.');
    dfs.setMonetaryDecimalSeparator('.');
    ((DecimalFormat) nf).setDecimalFormatSymbols(dfs);


    Vector<product> vec = new Vector<product>();
    gallery obj;

    obj=new product();
    obj.nama="Dark Chocolate";
    obj.price=Integer.parseInt(nf.format(3040000));
    obj.image="Image/Dark chocolate.jpg";
    vec.add(obj);

    obj = new product();
    obj.nama="Woodhouse Chocolates";
    obj.price=Integer.parseInt(nf.format(6000500));
    obj.image="Image/woodhouse_chocolates.jpg";
    vec.add(obj);

    obj = new product();
    obj.name="Semisweet Chocolate";
    obj.price=Integer.parseInt(nf.format(3050000));
    obj.image="Image/Semisweet chocolate.jpg";
    vec.add(obj);

    obj = new product();
    obj.name="White Chocolate";
    obj.price=Integer.parseInt(nf.format(2948000));
    obj.image="Image/White chocolate.jpg";
    vec.add(obj);

%>

它说

  

org.apache.jasper.JasperException:处理发生异常   JSP页面

在本节

 obj.price=Integer.parseInt(nf.format(3040000));
 obj.price=Integer.parseInt(nf.format(6000500));
 obj.price=Integer.parseInt(nf.format(3050000));
 obj.price=Integer.parseInt(nf.format(2948000));

我的错误在哪里?有谁可以帮助我?

3 个答案:

答案 0 :(得分:2)

您正在尝试使用一堆随机字符格式化数字 THEN 尝试将其解析为整数。

那不行。

An Integer是一个整数,没有小数部分,也没有花哨的字符。

如果您尝试将其解析为整数,则除0-9之外的任何字符(或负号)都将抛出NumberFormatException。

...(和 iangreen 说的那样)你应该把你的代码放在try块中。

... AND (比如 iangreen 说)您可以轻松地将此代码移动到其他可以测试/调试 LOT 的地方更容易(IDE或控制台程序)。

... AND 你应该总是用大写字母开始课程名称。


鉴于您在创建产品之前尝试格式化价格,您应该将它们存储在产品类中作为字符串。 OR 您可以将它们存储为双打或浮动,并在其他时间格式化它们。

答案 1 :(得分:2)

这绝对没有意义。您正在尝试将整数格式化为人类可读的String,然后将其解析回int,这在理论上会导致所有格式都丢失。 int无法存储格式。它应存储在String中。但是,当你这样做的时候是错误的,它应该在演示期间完成,而不是在预处理期间完成。您不应该使用格式String

使用JSTL <fmt:formatNumber>

<fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" />

它将以标准美元格式对其进行格式化,并自动为$货币符号添加前缀。

我也会将int更改为BigDecimal,否则您无法谈论实际价格格式。您无法在int中存储和显示分数。

答案 2 :(得分:1)

将代码包装在try / catch中并打印出异常。 更好的是 - 将代码移动到java类中并编写单元测试,以便在IDE中快速执行它