zoukankan      html  css  js  c++  java
  • Java实现数字转化成字符串左边自动补零方法

    Java 中给数字左边补0

    (1)方法一

    import java.text.NumberFormat;
    
    public class NumberFormatTest {
    
        public static void main(String[] args) {
            //待测试数据
            int i = 1;
            //得到一个NumberFormat的实例
            NumberFormat nf = NumberFormat.getInstance();
            //设置是否使用分组
            nf.setGroupingUsed(false);
            //设置最大整数位数
            nf.setMaximumIntegerDigits(4);
            //设置最小整数位数    
            nf.setMinimumIntegerDigits(4);
            //输出测试语句
            System.out.println(nf.format(i));
        }
    }


    (2)方法二(个人以为该方法简单有效,但经试验似乎String.format()函数有问题)

    public class TestStringFormat {      
      public static void main(String[] args) {      
        int youNumber = 1;      
        // 0 代表前面补充0      
        // 4 代表长度为4      
        // d 代表参数为正数型      
        String str = String.format("%04d", youNumber);      
        System.out.println(str); // 0001      
      }      
    }  

    有时候我们需要固定长度的字符串做流水号,每添加一个记录时流水号的值加1,
    而流水号的长度保持不变。

    一般的做法是先把流水号转换为数值型,然后此数值加1,再把数值转换为字符串,
    长度不够流水号长度时再在前面补0:

    //流水号加1后返回,流水号长度为4
    private static final String STR_FORMAT = "0000"; 
    
    public static String haoAddOne(String liuShuiHao){
        Integer intHao = Integer.parseInt(liuShuiHao);
        intHao++;
        DecimalFormat df = new DecimalFormat(STR_FORMAT);
        return df.format(intHao);
    }
  • 相关阅读:
    c#个人记录常用方法(更新中)
    Newtonsoft.Json.dll解析json的dll文件使用
    组织http请求
    ado.net中的几个对象
    jquery-easyui使用
    aspx与mvc页面验证码
    aspx页面状态管理(查询字符串Request与Application)
    aspx页面状态管理Cookie和ViewState
    在网页中插入qq连接
    ASP.NET中上传图片检测其是否为真实的图片 防范病毒上传至服务器
  • 原文地址:https://www.cnblogs.com/skyblue123/p/14485962.html
Copyright © 2011-2022 走看看