服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

在java开发过程中经常碰到数据类型的问题


  (1)在把int或double转换成bigdecimal时位数就会相应的增长,为了解决这个问题,可以将double获long型通过自写函数round进行四舍五入
    后,在转换成string,然后通过new bigdecimal()转换过来
   
    例如:fosum = new bigdecimal(string.&#118alueof(round(uo1sum.double&#118alue() + uo2sum.double&#118alue(),3)))
 
  (2)将时间转换成字符

        java.util.date date = new java.util.date(databean.gettyrq().gettime());
        simpledateformat sdf = new simpledateformat("yyyy-mm-dd");
        tyrq = sdf.format(date);

  (3)将字符串转换成时间timestamp类型
       public  java.sql.timestamp strtotimestamp(string str){
           java.sql.timestamp sdate = null;

    if(str!=null){

      if(str.trim().length()==8){
        str = str.substring(0,4)+"-"+str.substring(4,6)+"-"+str.substring(6,8);

      }
    try{
     dateformat df = dateformat.getdateinstance(dateformat.default,java.util.locale.china);
     java.util.date date = df.parse(str);
     sdate = new java.sql.timestamp(date.gettime());
    }catch(exception e){
      e.printstacktrace();
    }

}
  return sdate;
}
 
  (4)将double型进行四舍五入
     public  double round(double v,int scale){

       if(scale<0){

           throw new illegalargumentexception("the scale must be a positive integer or zero");

       }

       bigdecimal b = new bigdecimal(double.tostring(v));

       bigdecimal one = new bigdecimal("1");

       return b.divide(one,scale,bigdecimal.round_half_up).double&#118alue();

   }
  (5)将int转换成byte[]
     
    public byte[] inttobytearray(int num){
       int temp = num;
       byte[] b = new byte[6];
      for(int i=b.length;i>-1;i--){
      b[i] = new integer(temp&0xff).byte&#118alue();
        temp = temp >> 8;
      }
     return b;
    }
 
  (6)将int转换成byte
        int s=0;
        byte b = (byte)s;

扫描关注微信公众号