您的位置:首页 > 编程语言 > Java开发

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

2008-03-29 22:23 615 查看
(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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐