2012-06-19 78 views

回答

3
java.util.Formatter formatter = new java.util.Formatter(); 
formatter.format("%.2f", amount); 

欲瞭解更多信息,請參閱Formatter類的文檔。

您還可以使用DecimalFormat和稍微不同的語法。

+0

我正在使用jsp。據我所知printf不支持jsp在網頁中顯示。 謝謝 – Mehedi

+0

@Mehedi:我編輯了我的帖子。你可以測試這種方法嗎? – nhahtdh

+0

謝謝nhahtdh。這是工作 – Mehedi

0

add <@page import="java.math.BigDecimal"> to your jsp first 

    <% 
     BigDecimal bigd=new BigDecimal(); 
     bigd=bigd.setScale(2,BigDecimal.ROUND_HALF_EVEN); 
     out.println(bigd); 
    %> 
+0

感謝您的答覆。但它不能解決我的問題。如果我使用此代碼發生一個錯誤。錯誤是:「無法找到符號 符號:類BigDecimal location:class SimplifiedJSPServlet」 – Mehedi

+0

add <%@ page import =「java.math.BigDecimal」%>給你的jsp第一個 – user965347

3

添加下面的代碼行JSP頁面的頂部。

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 

然後用下面的代碼行,以顯示你的數字

<fmt:formatNumber type="number" maxFractionDigits="2" value="${amount}"/> 

這裏maxFractionDigits屬性被用來定義你想要多少位數字小數點後顯示。

+1

最佳答案,但是,如果OP有' 123.2'作爲十進制,你的代碼實際上會打印出'123.2'。包含'minFractionDigits =「2」'將使其打印'123.20'。 – FelipeKunzler