常用数值转换
常用数值转换
package tools;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;/* * public int stringToInt(String str)***主要方法 int i=Integer.parseInt(str);; String 转换为Int * public String intToString(int i)===主要方法 String str=Integer.toString(i); Int转换为String * public float strTofloat(String str)***主要方法 Float fnum=Float.parseFloat(str) String转换为Float * public String floatToStr(Float fnum)***主要方法 String str=Float.toString(fnum);// Float转换为String * public static Double strToDouble(String str)*** String转换为Double * public static String doubleToStr(Double dnum)//Double转换为String * public static String dateToString(Date date) 将date类型转换为String类型 * public static Date stringToDate(String str) 将String类型转换为日期类型 * public static java.sql.Date uDateToSqlDate(java.util.Date udate) 将java.util.date类型转换为java.sql.date类型 */public class StrTools {//String 转换为Intpublic static int stringToInt(String str){int i = 0;try{i=Integer.parseInt(str);}catch(Exception e){e.printStackTrace();i=-1;}return i;}//Int转换为Stringpublic static String intToString(int i){String str="";try {str=Integer.toString(i);} catch (RuntimeException e) {e.printStackTrace();str="";}return str;}//String转换为Floatpublic static float strTofloat(String str){float fnum=0;try {fnum=Float.parseFloat(str);} catch (NumberFormatException e) {e.printStackTrace();fnum=-1;}return fnum;}//Float转换为Stringpublic static String floatToStr(Float fnum){String str="";try {str=Float.toString(fnum);} catch (NumberFormatException e) {e.printStackTrace();}return str;}//String转换为Doublepublic static Double strToDouble(String str){Double dnum = null;try {dnum=Integer.valueOf(str).doubleValue();} catch (NumberFormatException e) {e.printStackTrace();}return dnum;}//Double转换为Stringpublic static String doubleToStr(Double dnum){String str="";try {str=Double.toString(dnum);} catch (NumberFormatException e) {e.printStackTrace();}return str;}//将date类型转换为String类型public static String dateToString(Date date){String dateStr="";if(date!=null){SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");dateStr=sf.format(date);}return dateStr;}//将String类型转换为日期类型public static Date stringToDate(String str){SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");Date date=null;if(str==null||str.length()<8)return null;try{date=sdf.parse(str);}catch(ParseException e){e.printStackTrace();}return date;}//将java.util.date类型转换为java.sql.date类型public static java.sql.Date uDateToSqlDate(java.util.Date udate){java.sql.Date date=null;try {date=new java.sql.Date(udate.getTime());} catch (RuntimeException e) {e.printStackTrace();}return date;}public static void main(String []args){Date date=StrTools.stringToDate("2009-01-01");System.out.println(date);String dates=StrTools.dateToString(date);System.out.println(dates);}}