我有以下问题。我正在使用一个使用JQuery的JSP页面。
在这个页面中,我将一些金额显示在表格中,如下所示:
<td width = "8.33%">
<%=salDettaglio.getTotImponibile().toString() != null ? salDettaglio.getTotImponibile().toString() : "" %>
</td>
获取的对象(来自getTotImponibile()方法)是一个BigDecimal
在我的表格中,它显示的值为: 447.93 。
现在我必须按以下方式格式化这个数量:
使用,字符代替。(小数位数字)。
在之后总是显示2位小数。例如,我只能有一个十进制数字作为10,4而且我必须显示10,40或者我可以有超过2位小数数字,在这种情况下,我只需要显示第一个2位十进制数字(例如10,432所以我必须显示10,43)
那么我该怎么做才能完成这两项任务呢?实际上我正在显示一个代表十进制数字的字符串。我是否要将此值转换为双倍或类似的东西?
答案 0 :(得分:2)
首先创建一个类(即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>
此解决方案适合您。
答案 1 :(得分:1)
如果您有以下内容:
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()) %>
答案 2 :(得分:0)
答案 3 :(得分:0)
恕我直言,我不会从代码中格式化数字/值,因为它是JSP的任务(项目的视图部分)。
为什么不使用JSTL?
http://www.tutorialspoint.com/jsp/jstl_format_formatnumber_tag.htm
这样你就可以保持原样,另一方面,你可以根据视图给它准确的格式。