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 value="${balance}" type="currency"/></p>
<p>จัดรูปแบบ (2): <fmt:formatNumber type="number" maxIntegerDigits="3" value="${balance}" /></p>
<p>จัดรูปแบบ (3): <fmt:formatNumber type="number" maxFractionDigits="3" value="${balance}" /></p>
<p>จัดรูปแบบ (4): <fmt:formatNumber type="number" groupingUsed="false" value="${balance}" /></p>
</body>
</html>

ผลลัพธ์

การจัดรูปแบบตัวเลข:
จัดรูปแบบ (1): $120,000.23
จัดรูปแบบ (2): 000.231
จัดรูปแบบ (3): 120,000.231
จัดรูปแบบ (4): 120000.231

คำอธิบาย:

  • (1) แสดงเป็นสกุลเงินตาม Locale เริ่มต้น (มีคอมม่าคั่นหลักพัน)
  • (2) จำกัดหลักเต็มสูงสุด 3 หลัก แสดงแค่ 3 หลักท้าย
  • (3) จำกัดหลักทศนิยมสูงสุด 3 หลัก
  • (4) ปิดการจัดกลุ่มตัวเลข (ไม่มีคอมม่า)