我有以下问题。我正在开发一个使用 JQuery 的 JSP 页面。
在此页面中,我将一些金额显示在表格中,如下所示:
<td width = "8.33%">
<%=salDettaglio.getTotImponibile().toString() != null ? salDettaglio.getTotImponibile().toString() : "" %>
</td>
获得的对象(来自getTotImponibile((方法(是一个BigDecimal
在我的表格的 td 中,它显示的值为:447.93。
现在我必须按以下方式格式化此金额:
使用 , 字符代替 . (对于十进制数字(。
在 .例如,我只能有一个十进制数字作为 10,4,我必须显示 10,40,或者我可以有超过 2 个十进制数字,在这种情况下,我只需要显示 2 个十进制数字(例如 10,432,所以我必须显示 10,43(
那么我该怎么做才能完成这两项任务呢?实际上,我正在显示一个表示十进制数的字符串。我必须将此值转换为双精度值或类似的东西吗?
首先创建一个类(即 NumberFormat.java(,请在 NumberFormat.java 类中输入以下方法:
public static String priceWithDecimal (Double price) {
DecimalFormat formatter = new DecimalFormat("###,###,###.00");
return formatter.format(price);
}
public static String priceWithoutDecimal (Double price) {
DecimalFormat formatter = new DecimalFormat("###,###,###.##");
return formatter.format(price);
}
现在,在你的jsp中使用这样的代码:
<td width = "8.33%">
<%=salDettaglio.getTotImponibile().toString() != null ? NumberFormat.priceWithDecimal(Double.parseDouble(salDettaglio.getTotImponibile().toString())) : "" %>
</td>
此解决方案将为您服务。
如果您有类似以下内容的内容:
class Helpers
{
public static String getMoneyFormat( BigDecimal money )
{
if ( money == null ) return "";
DecimalFormat df = new DecimalFormat("###,##0.00");
return df.format(money);
}
}
然后将其包含在您的 JSP 页面中,然后您将能够执行以下操作:
<%= Helpers.getMoneyFormat(salDettaglio.getTotImponibile()) %>
在salDettaglio.getTotImponibile()
中,不是返回数字,而是使用 NumberFormat 返回格式化字符串
这是一个带有示例的简单教程。
注意:一切都在谷歌中
我直言,我不会格式化代码中的数字/值,因为它是 JSP(项目的视图部分(的任务。
为什么不使用 JSTL 呢?
http://www.tutorialspoint.com/jsp/jstl_format_formatnumber_tag.htm
这样,您将保持值不变,另一方面,您可以根据视图为其提供精确的格式。