JavaBean专题

将整型数据格式化为指定长度的字符串

2018-08-18  本文已影响0人  神坛下的我

StringUtil7.java

import java.text.NumberFormat;

public class StringUtil7 {
    private int intValue;//将要格式化的整型值
    private String formatStr;//格式化后的字符串
    private int minimumDigit;//字符串的最少位数
    public StringUtil7(){}
    public int getIntValue() {
        return intValue;
    }
    public void setIntValue(int intValue) {
        this.intValue = intValue;
    }
    public String getFormatStr() {
        NumberFormat nf= NumberFormat.getInstance();
        nf.setMinimumIntegerDigits(minimumDigit);
        return nf.format(intValue).replace(",", "");//把字符串中的,替换掉
    }
    public void setFormatStr(String formatStr) {
        this.formatStr = formatStr;
    }
    public int getMinimumDigit() {
        return minimumDigit;
    }
    public void setMinimumDigit(int minimumDigit) {
        this.minimumDigit = minimumDigit;
    }
    
}

index.jsp

<body>
    <form action="result.jsp" method="post">
        <table>
            <tr>
                <td align="right">请输入要格式化的数字:</td>
                <td><input type="text" name="num"/></td>
            </tr>
            <tr>
                <td align="right">请输入格式化后的字符串长度:</td>
                <td><input type="text" name="length"/></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="格式化"/></td>
            </tr>
        </table>
    </form>
</body>

result.jsp

<body>
    <%
        request.setCharacterEncoding("utf-8");
        String num=request.getParameter("num");
        String length=request.getParameter("length");
        int n=Integer.parseInt(num);
        int l=Integer.parseInt(length);
    %>
    <jsp:useBean id="strBean" class="com.count.StringUtil7"></jsp:useBean>
    <jsp:setProperty property="intValue" name="strBean" value="<%=n %>"/>
    <jsp:setProperty property="minimumDigit" name="strBean" value="<%=l %>"/>
    <table>
        <tr>
            <td>格式化之前的数字:</td>
            <td align="left">
                <jsp:getProperty property="intValue" name="strBean"/>
            </td>
        </tr>
        <tr>
            <td>格式化之后的字符串:</td>
            <td align="left">
                <jsp:getProperty property="formatStr" name="strBean"/>
            </td>
        </tr>
    </table>
</body>
10.PNG 11.PNG 12.PNG
上一篇下一篇

猜你喜欢

热点阅读