java元转分 分转元的 几种写法
/**
* 元转分,确保price保留两位有效数字
* @return
*/
public static int changeY2F(double price) {
DecimalFormat df = new DecimalFormat("#.00");
price = Double.valueOf(df.format(price));
int money = (int)(price * 100);
return money;
}
/**
* 元转换成分
* @param money
* @return
*/
public static String getMoney(String amount) {
if(amount==null){
return "";
}
// 金额转化为分为单位
String currency = amount.replaceAll("\\$|\\¥|\\,", ""); //处理包含, ¥ 或者$的金额
int index = currency.indexOf(".");
int length = currency.length();
Long amLong = 0l;
if(index == -1){
amLong = Long.valueOf(currency+"00");
}else if(length - index >= 3){
amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", ""));
}else if(length - index == 2){
amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0);
}else{
amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");
}
return amLong.toString();
}
/**
* 分转元,转换为bigDecimal在toString
* @return
*/
public static String changeF2Y(int price) {
return BigDecimal.valueOf(Long.valueOf(price)).divide(new BigDecimal(100)).toString();
}
/**
* 分转元,转换为bigDecimal在转成double
* @return
*/
public static double changeF2Y3(int price) {
return BigDecimal.valueOf(Long.valueOf(price)).divide(new BigDecimal(100)).doubleValue();
}