JavaBean专题

将长整型的数字分位显示

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

StringUtil7.java

public class StringUtil7 {
    private long longValue;//要分位的数字
    private int digit;//分位位数
    private String formatStr;//分位后的字符串
    public StringUtil7(){}
    public long getLongValue() {
        return longValue;
    }
    public void setLongValue(long longValue) {
        this.longValue = longValue;
    }
    public int getDigit() {
        return digit;
    }
    public void setDigit(int digit) {
        this.digit = digit;
    }
    public String getFormatStr() {
        StringBuffer sb= new StringBuffer(String.valueOf(longValue));
        sb=sb.reverse();//反转
        int l=sb.length();
        if(digit==0)    digit=1;//如果分位位数为0,设置字符串的长度为分位位数
        int count=0;
        /*计算出插入的分位符个数*/
        if(l%digit==0)  count=l/digit-1;
        else count=l/digit;
        for (int i = 0; i < count; i++) {
            sb=sb.insert((i+1)*digit+i, ",");//在分位位置插入分位符
        }
        
        return sb.reverse().toString();
    }
    public void setFormatStr(String formatStr) {
        this.formatStr = formatStr;
    }
    
    
}

index.jsp

<body>
    <form action="result.jsp" method="post">
        <table>
            <tr>
                <td align="right">请输入数字:</td>
                <td><input type="text" name="longValue"/></td>
            </tr>
            <tr>
                <td align="right">请输入分位位数:</td>
                <td><input type="text" name="digit"/></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 longValueStr= request.getParameter("longValue");
        String digit=request.getParameter("digit");
        long longValue=Long.parseLong(longValueStr);
        int d= Integer.parseInt(digit);
    %>
    <jsp:useBean id="strBean" class="com.count.StringUtil7"></jsp:useBean>
    <jsp:setProperty property="longValue" name="strBean" value="<%=longValue %>"/>
    <jsp:setProperty property="digit" name="strBean" value="<%=d %>"/>
    <table>
        <tr>
            <td>分位之前的数字:</td>
            <td align="left">
                <jsp:getProperty property="longValue" name="strBean"/>
            </td>
        </tr>
        <tr>
            <td>分位之后的字符串:</td>
            <td align="left">
                <jsp:getProperty property="formatStr" name="strBean"/>
            </td>
        </tr>
    </table>
</body>
13.PNG 14.PNG 15.PNG 16.PNG
上一篇下一篇

猜你喜欢

热点阅读