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

java中常用数据类型转换器

2015-08-15 16:08 483 查看
/**
*把String转换成long
*
*@paramsrc要转换的String
*@paramdef转换失败时返回此值
*@return转换好的long
*/

publicstaticlongtoLong(Stringsrc,longdef){
if(src==null){
returndef;
}
try{
returnLong.parseLong(src);
}catch(Exceptionignore){
}
returndef;
}

/**
*把String转换成int
*
*@paramsrc要转换的String
*@paramdef转换失败时返回此值
*@return转换好的int
*/
publicstaticinttoInt(Stringsrc,intdef){
if(src==null){
returndef;
}
try{
returnInteger.parseInt(src);
}catch(Exceptionignore){
}
returndef;
}

/**
*把String转换成byte
*
*@paramsrc要转换的String
*@paramdef转换失败时返回此值
*@return转换好的intbyte
*/
publicstaticbytetoByte(Stringsrc,bytedef){
if(src==null){
returndef;
}
try{
returnByte.parseByte(src);
}catch(Exceptionignore){
}
returndef;
}

/**
*String转换成Date
*
*@paramdateString
*@parampattern样式
*@returnDate
*/
publicstaticDatetoDate(Stringdate,Stringpattern){
if(date==null||pattern==null){
returnnull;
}
try{
SimpleDateFormatformat=newSimpleDateFormat(pattern);
returnformat.parse(date);
}catch(Exceptionignore){
}
returnnull;
}


/**
*分转元转换,保留两位小数
*@paramsrcValue源数据
*@return结果
*/
publicstaticdoublelongToMoney(longsrcValue){
BigDecimalobj=newBigDecimal(srcValue);
doublecny=obj.divide(newBigDecimal(100)).doubleValue();
returnDouble.parseDouble(String.format("%.2f",cny));
}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: