반응형
JSTL round 커스텀 함수 만들기
먼저 jstl round 함수를 만드는 이유는 formatting 버그가 발생되었기 때문이다.
<fmt:formatNumber var="TEST1" value="${10.625}" pattern="#.##"/>
이라고 입력하면 이상하게도 출력되는 값은 '10.62'가 출력된다.
하지만, '10.6251' 으로 입력하면 '10.63'으로 정상적으로 반올림되어 출력이된다.
FormatNumberTag 후... ㅠ
정말 말도 안되는 버그다. 나만 이런가....
그래서 태그라이브러리에 커스텀 함수를 추가하기로 했다.
1. 태그라이브러리 생성
/WEB-INF/tlds/customTag.tld 위 경로에 tld 파일 생성해준다.
메모장으로 내용없이 확장자만 tld로 만들어주고 넣어도 된다.
내용은 다음과 같다.
붉은 색 네모를 주의하면서 작성하자
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>Out Filter Custom Tag</description>
<tlib-version>1.0</tlib-version>
<short-name>cst</short-name>
<uri>/WEB-INF/tlds/customTag.tld</uri>
<function>
<name>round</name>
<function-class>kr.re.kedi.common.util.CustomTag</function-class>
<function-signature>java.lang.String round(java.lang.String, java.lang.String)</function-signature>
</function>
</taglib>
2. java 파일 생성
round함수를 사용할 java파일을 별도로 생성해주자.
package kr.re.kedi.common.util;
public class CustomTag {
public static String round(String str, String str2){
String ret = "";
try{
float f = Float.valueOf(str.trim()).floatValue();
int i = Integer.parseInt(str2);
double n = Math.pow(10.0, i);
ret = String.valueOf( Math.round( f * n ) / n );
}
catch (Exception e){
ret = "0";
}
return ret;
}
}
3. jsp 맨 위에 태그 라이브러리를 불러주자.
<%@ taglib prefix="cst" uri="/WEB-INF/tlds/customTag.tld" %>
4. 커스텀 함수 사용하기
<c:out value="${cst:round(100.625, 2)}"/>
cst라는 커스텀 태그를 만들고, round 함수를 만들었다. 사용방법도 참 쉽죠?
반응형