Java 如何格式化JSP页面中表示十进制数的字符串?
我有以下问题。我正在处理一个使用JQuery的JSP页面 在本页中,我将一些金额显示在一个表中,如下所示:Java 如何格式化JSP页面中表示十进制数的字符串?,java,jsp,casting,double,Java,Jsp,Casting,Double,我有以下问题。我正在处理一个使用JQuery的JSP页面 在本页中,我将一些金额显示在一个表中,如下所示: <td width = "8.33%"> <%=salDettaglio.getTotImponibile().toString() != null ? salDettaglio.getTotImponibile().toString() : "" %> </td> <td width = "8.33%"> <%=sa
<td width = "8.33%">
<%=salDettaglio.getTotImponibile().toString() != null ? salDettaglio.getTotImponibile().toString() : "" %>
</td>
<td width = "8.33%">
<%=salDettaglio.getTotImponibile().toString() != null ? NumberFormat.priceWithDecimal(Double.parseDouble(salDettaglio.getTotImponibile().toString())) : "" %>
</td>
获取的对象(来自getToImpoibile()方法)是一个BigDecimal
在我的表格的td中,它的值显示为:447.93
现在,我必须按以下方式格式化此金额:
那么,我能做些什么来完成这两项任务呢?实际上,我正在显示一个表示十进制数的字符串。我必须将此值转换为double或类似的值吗?在您的
saldetaglio.getToImponifile()
中,而不是返回数字,而是使用
这是一个带有示例的简单教程
注意:一切都在google中首先创建一个类(即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 ? salDettaglio.getTotImponibile().toString() : "" %>
</td>
<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);
}
}
<%= Helpers.getMoneyFormat(salDettaglio.getTotImponibile()) %>
然后将其包含在JSP页面中,您将能够执行以下操作:
class Helpers
{
public static String getMoneyFormat( BigDecimal money )
{
if ( money == null ) return "";
DecimalFormat df = new DecimalFormat("###,##0.00");
return df.format(money);
}
}
<%= Helpers.getMoneyFormat(salDettaglio.getTotImponibile()) %>
我不想格式化代码中的数字/值,因为这是JSP的任务(项目的视图部分) 为什么不改用JSTL呢
这样,您将保持值的原样,另一方面,您可以根据视图为其提供精确的格式。请为我的previos示例演示一个简单的代码片段。我将使用NumberFormat,但正如我在回答中解释的JSTL。