Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

วิธีจัดรูปแบบเปอร์เซ็นต์ใน JSP ด้วย JSTL fmt:formatNumber


แท็ก <fmt:formatNumber> ใช้สำหรับจัดรูปแบบการแสดงผลของ ตัวเลข, เปอร์เซ็นต์ และ สกุลเงิน ใน JSP

แอตทริบิวต์ของ <fmt:formatNumber>

แอตทริบิวต์ คำอธิบาย จำเป็น ค่าเริ่มต้น
value ค่าตัวเลขที่ต้องการจัดรูปแบบ ใช่ None
type ประเภท: NUMBER, CURRENCY, หรือ PERCENT ไม่ Number
pattern รูปแบบการจัดรูปแบบแบบกำหนดเอง ไม่ None
currencyCode รหัสสกุลเงิน (สำหรับ type="currency") ไม่ From the default locale
currencySymbol สัญลักษณ์สกุลเงิน (สำหรับ type="currency") ไม่ From the default locale
groupingUsed ใช้การจัดกลุ่มตัวเลข (true/false) ไม่ true
maxIntegerDigits จำนวนหลักเต็มสูงสุด ไม่ None
minIntegerDigits จำนวนหลักเต็มขั้นต่ำ ไม่ None
maxFractionDigits จำนวนหลักทศนิยมสูงสุด ไม่ None
minFractionDigits จำนวนหลักทศนิยมขั้นต่ำ ไม่ None
var ชื่อตัวแปรเก็บผลลัพธ์ ไม่ Print to page
scope ขอบเขตของตัวแปร ไม่ page

ตัวอย่างการใช้งาน

<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="https://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>JSTL fmt:formatNumber Tag - จัดรูปแบบเปอร์เซ็นต์</title>
</head>
<body>
<h3>การจัดรูปแบบตัวเลข:</h3>
<c:set var="balance" value="120000.2309" />
<p>จัดรูปแบบ (1): <fmt:formatNumber type="percent" maxIntegerDigits="3" value="${balance}" /></p>
<p>จัดรูปแบบ (2): <fmt:formatNumber type="percent" minFractionDigits="10" value="${balance}" /></p>
<p>จัดรูปแบบ (3): <fmt:formatNumber type="percent" maxIntegerDigits="3" value="${balance}" /></p>
</body>
</html>

ผลลัพธ์

การจัดรูปแบบตัวเลข:
จัดรูปแบบ (1): 12,000,023%
จัดรูปแบบ (2): 12,000,023.0900000000%
จัดรูปแบบ (3): 12,000,023%

หมายเหตุ: ค่า 120000.2309 เมื่อจัดรูปแบบเป็นเปอร์เซ็นต์จะคูณ 100 กลายเป็น 12,000,023.09% แอตทริบิวต์ maxIntegerDigits จำกัดหลักเต็ม minFractionDigits กำหนดหลักทศนิยมขั้นต่ำ