java中常用資料類型轉換器

來源:互聯網
上載者:User

標籤:

/**
* 把String轉換成long
*
* @param src 要轉換的String
* @param def 轉換失敗時返回此值
* @return 轉換好的long
*/
public static long toLong(String src, long def) {
if (src == null) {
return def;
}
try {
return Long.parseLong(src);
} catch (Exception ignore) {
}
return def;
}

/**
* 把String轉換成int
*
* @param src 要轉換的String
* @param def 轉換失敗時返回此值
* @return 轉換好的int
*/
public static int toInt(String src, int def) {
if (src == null) {
return def;
}
try {
return Integer.parseInt(src);
} catch (Exception ignore) {
}
return def;
}

/**
* 把String轉換成byte
*
* @param src 要轉換的String
* @param def 轉換失敗時返回此值
* @return 轉換好的intbyte
*/
public static byte toByte(String src, byte def) {
if (src == null) {
return def;
}
try {
return Byte.parseByte(src);
} catch (Exception ignore) {
}
return def;
}

/**
* String轉換成Date
*
* @param date String
* @param pattern 樣式
* @return Date
*/
public static Date toDate(String date, String pattern) {
if (date == null || pattern == null) {
return null;
}
try {
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.parse(date);
} catch (Exception ignore) {
}
return null;
}

/**
* 分轉元轉換,保留兩位小數
* @param srcValue 來源資料
* @return 結果
*/
public static double longToMoney(long srcValue) {
BigDecimal obj = new BigDecimal(srcValue);
double cny = obj.divide(new BigDecimal(100)).doubleValue();
return Double.parseDouble(String.format("%.2f", cny));
}
 
 

java中常用資料類型轉換器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.